Skip to main content

db_redis/
connection.rs

1use redis::{
2    AsyncCommands, Cmd, FromRedisValue, RedisResult, ToRedisArgs, aio::ConnectionManager,
3    cluster_async::ClusterConnection,
4};
5
6pub enum RedisConnection {
7    Single(ConnectionManager),
8    Cluster(ClusterConnection),
9}
10
11impl RedisConnection {
12    pub async fn query<T: FromRedisValue>(&mut self, cmd: &mut Cmd) -> RedisResult<T> {
13        match self {
14            RedisConnection::Single(client) => cmd.query_async(client).await,
15            RedisConnection::Cluster(client) => cmd.query_async(client).await,
16        }
17    }
18    pub async fn exec(&mut self, cmd: &mut Cmd) -> RedisResult<()> {
19        match self {
20            RedisConnection::Single(client) => cmd.exec_async(client).await,
21            RedisConnection::Cluster(client) => cmd.exec_async(client).await,
22        }
23    }
24    pub async fn publish<C, M>(&mut self, channel: C, message: M) -> RedisResult<()>
25    where
26        C: ToRedisArgs + Send + Sync,
27        M: ToRedisArgs + Send + Sync,
28    {
29        match self {
30            RedisConnection::Single(client) => client.publish(channel, message).await?,
31            RedisConnection::Cluster(client) => client.publish(channel, message).await?,
32        }
33        Ok(())
34    }
35}