soph_redis/support/
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
use crate::{config, error::Error, Redis, RedisResult};
use bb8_redis::{bb8::Pool, redis::cmd, RedisConnectionManager};
use std::time::Duration;

impl Redis {
    pub async fn try_from_config(config: config::Redis) -> RedisResult<Self> {
        let manager = RedisConnectionManager::new(config.url.to_string())?;

        let pool = Pool::builder()
            .max_size(config.max_size)
            .min_idle(config.min_idle)
            .test_on_check_out(config.test_on_check_out)
            .max_lifetime(Duration::from_millis(config.max_lifetime))
            .idle_timeout(Duration::from_millis(config.idle_timeout))
            .connection_timeout(Duration::from_millis(config.connection_timeout))
            .retry_connection(config.retry_connection)
            .reaper_rate(Duration::from_millis(config.reaper_rate))
            .build(manager)
            .await?;

        Ok(Self { pool })
    }

    // https://docs.rs/bb8-redis/0.15.0/bb8_redis/
    pub async fn ping(&self) -> RedisResult<()> {
        let mut conn = self.get().await?;

        let reply: String = cmd("PING").query_async(&mut *conn).await?;

        if "PONG" != reply {
            return Err(Error::RedisPing);
        }

        Ok(())
    }
}

impl std::ops::Deref for Redis {
    type Target = Pool<RedisConnectionManager>;

    fn deref(&self) -> &Self::Target {
        &self.pool
    }
}