actix_cloud/memorydb/
redis.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::time::Duration;

use async_trait::async_trait;
use redis::{aio::ConnectionManager, AsyncCommands, Expiry};

use super::interface::MemoryDB;
use crate::Result;

#[derive(Clone)]
pub struct RedisBackend {
    client: ConnectionManager,
}

impl RedisBackend {
    pub async fn new(dsn: &str) -> Result<Self> {
        let client = ConnectionManager::new(redis::Client::open(dsn)?).await?;
        Ok(Self { client })
    }
}

#[async_trait]
impl MemoryDB for RedisBackend {
    async fn set(&self, key: &str, value: &str) -> Result<()> {
        self.client
            .clone()
            .set(key, value)
            .await
            .map_err(Into::into)
    }

    async fn get(&self, key: &str) -> Result<Option<String>> {
        self.client.clone().get(key).await.map_err(Into::into)
    }

    async fn get_del(&self, key: &str) -> Result<Option<String>> {
        self.client.clone().get_del(key).await.map_err(Into::into)
    }

    async fn get_ex(&self, key: &str, ttl: &Duration) -> Result<Option<String>> {
        self.client
            .clone()
            .get_ex(key, Expiry::EX(ttl.as_secs()))
            .await
            .map_err(Into::into)
    }

    async fn set_ex(&self, key: &str, value: &str, ttl: &Duration) -> Result<()> {
        self.client
            .clone()
            .set_ex(key, value, ttl.as_secs())
            .await
            .map_err(Into::into)
    }

    async fn del(&self, key: &str) -> Result<bool> {
        self.client.clone().del(key).await.map_err(Into::into)
    }

    async fn expire(&self, key: &str, ttl: i64) -> Result<bool> {
        self.client
            .clone()
            .expire(key, ttl)
            .await
            .map_err(Into::into)
    }

    async fn flush(&self) -> Result<()> {
        redis::cmd("FLUSHDB")
            .query_async(&mut self.client.clone())
            .await
            .map_err(Into::into)
    }

    async fn keys(&self, key: &str) -> Result<Vec<String>> {
        self.client.clone().keys(key).await.map_err(Into::into)
    }

    async fn dels(&self, keys: &[String]) -> Result<u64> {
        let mut p = redis::pipe();
        let mut p = p.atomic();
        for i in keys {
            p = p.del(i);
        }
        let res: Vec<u64> = p.query_async(&mut self.client.clone()).await?;
        Ok(res.into_iter().sum())
    }
}