1use std::collections::HashMap;
2
3use redis::{aio::MultiplexedConnection, AsyncCommands, Client, FromRedisValue, RedisResult};
4
5#[derive(Debug, Clone)]
6pub struct RedisClient {
7 pub db_name: String,
8 pub client: Client,
9}
10
11impl RedisClient {
12 pub fn connect(url: &str, db_name: &str) -> RedisResult<Self> {
13 let client = Client::open(url)?;
14 Ok(Self {
15 client,
16 db_name: db_name.to_string(),
17 })
18 }
19
20 pub async fn get_con(&self) -> RedisResult<MultiplexedConnection> {
21 self.client.get_multiplexed_async_connection().await
22 }
23
24 pub async fn set_str(&self, key: &str, value: &str, ttl_seconds: i64) -> RedisResult<()> {
25 let mut con = self.get_con().await?;
26 con.set(key, value).await?;
27 if ttl_seconds > 0 {
28 con.expire(key, ttl_seconds).await?;
29 }
30 Ok(())
31 }
32
33 pub async fn hset(&self, key: &str, field: &str, value: &str) -> RedisResult<()> {
34 let mut con = self.get_con().await?;
35 con.hset(key, field, value).await
36 }
37
38 pub async fn hget(&self, key: &str, field: &str) -> RedisResult<String> {
39 let mut con = self.get_con().await?;
40 con.hget(key, field).await
41 }
42
43 pub async fn hgetall(&self, key: &str) -> RedisResult<HashMap<String, String>> {
44 let mut con = self.get_con().await?;
45 let val = con.hgetall(key).await?;
46 FromRedisValue::from_redis_value(&val)
47 }
48
49 pub async fn hdel(&self, key: &str, field: &str) -> RedisResult<()> {
50 let mut con = self.get_con().await?;
51 con.hdel(key, field).await
52 }
53
54 pub async fn get_str(&self, key: &str) -> RedisResult<String> {
55 let mut con = self.get_con().await?;
56 let value = con.get(key).await?;
57 FromRedisValue::from_redis_value(&value)
58 }
59}