genies_cache/
cache_service.rs

1use std::time::Duration;
2
3/*
4 * @Author: tzw
5 * @Date: 2021-10-17 21:43:48
6 * @LastEditors: tzw
7 * @LastEditTime: 2021-12-22 00:16:26
8 */
9use genies_config::app_config::ApplicationConfig;
10
11use async_trait::async_trait;
12use genies_core::Result;
13// use prost::Message;
14use serde::de::DeserializeOwned;
15use serde::Serialize;
16
17use crate::redis_service::RedisService;
18use crate::mem_service::MemService;
19use genies_core::error::Error;
20
21#[async_trait]
22pub trait ICacheService: Sync + Send {
23    async fn set_string(&self, k: &str, v: &str) -> Result<String>;
24    async fn get_string(&self, k: &str) -> Result<String>;
25    async fn del_string(&self, k: &str) -> Result<String>;
26    async fn set_string_ex(&self, k: &str, v: &str, ex: Option<Duration>) -> Result<String>;
27    async fn set_value(&self, k: &str, v: &[u8]) -> Result<String>;
28    async fn get_value(&self, k: &str) -> Result<Vec<u8>>;
29    async fn set_value_ex(&self, k: &str, v: &[u8], ex: Option<Duration>) -> Result<String>;
30    async fn ttl(&self, k: &str) -> Result<i64>;
31}
32
33pub struct CacheService {
34    pub inner: Box<dyn ICacheService>,
35}
36
37impl CacheService {
38    pub fn new(cfg: &ApplicationConfig) -> Self {
39        Self {
40            inner: match cfg.cache_type.as_str() {
41                "redis" => Box::new(RedisService::new(&cfg.redis_url)),
42                //"mem"
43                _ => Box::new(MemService::default()),
44            },
45        }
46    }
47    pub fn new_saved(cfg: &ApplicationConfig) -> Self {
48        Self {
49            inner: match cfg.cache_type.as_str() {
50                "redis" => Box::new(RedisService::new(&cfg.redis_save_url)),
51                //"mem"
52                _ => Box::new(MemService::default()),
53            },
54        }
55    }
56    pub async fn set_string(&self, k: &str, v: &str) -> Result<String> {
57        self.inner.set_string(k, v).await
58    }
59
60    pub async fn get_string(&self, k: &str) -> Result<String> {
61        self.inner.get_string(k).await
62    }
63    pub async fn del_string(&self, k: &str) -> Result<String> {
64        self.inner.del_string(k).await
65    }
66
67    pub async fn set_json<T>(&self, k: &str, v: &T) -> Result<String>
68    where
69        T: Serialize + Sync,
70    {
71        let data = serde_json::to_string(v);
72        if data.is_err() {
73            return Err(Error::from(format!(
74                "MemCacheService set_json fail:{}",
75                data.err().unwrap()
76            )));
77        }
78        let data = self.set_string(k, data.unwrap().as_str()).await?;
79        Ok(data)
80    }
81
82    pub async fn get_json<T>(&self, k: &str) -> Result<T>
83    where
84        T: DeserializeOwned + Sync,
85    {
86        let mut r = self.get_string(k).await?;
87        if r.is_empty() {
88            r = "null".to_string();
89        }
90        let data: serde_json::Result<T> = serde_json::from_str(r.as_str());
91        if data.is_err() {
92            return Err(Error::from(format!(
93                "MemCacheService GET fail:{}",
94                data.err().unwrap()
95            )));
96        }
97        Ok(data.unwrap())
98    }
99
100    pub async fn set_string_ex(&self, k: &str, v: &str, ex: Option<Duration>) -> Result<String> {
101        self.inner.set_string_ex(k, v, ex).await
102    }
103    // pub async fn set_object_use_protobuf<T: Message + Default>(
104    //     &self,
105    //     k: &str,
106    //     _v: &T,
107    // ) -> Result<String> {
108    //     let  bytes = Vec::new();
109    //     // let t = v.encode(&mut bytes).unwrap();
110    //     // let b=bytes;
111    //     self.inner.set_value(k, &bytes).await
112    // }
113    //
114    // pub async fn get_object_use_protobuf<T: Message + Default>(&self, k: &str) -> Result<T> {
115    //     let r = self.inner.get_value(k).await?;
116    //     let v: T = T::decode(&*r).unwrap();
117    //     return Ok(v);
118    // }
119    //
120    pub async fn ttl(&self, k: &str) -> Result<i64> {
121        self.inner.ttl(k).await
122    }
123}
124
125// fn some_function() -> Result<(), Error> {
126//     // ... existing code ...
127//     if some_condition {
128//         return Err(Error::from(format!("Some error message")));
129//     }
130//     // ... existing code ...
131// }