修改内存缓存的有效期业务

This commit is contained in:
李运家 2025-02-14 14:15:53 +08:00
parent fe5dd45cfd
commit ddb12f02f3

View File

@ -30,7 +30,7 @@ impl<D> ServerCache<String, D>
where where
D: Debug + Send + Sync + Clone + Serialize + DeserializeOwned + 'static, D: Debug + Send + Sync + Clone + Serialize + DeserializeOwned + 'static,
{ {
fn default(cache_type: &str) -> Self { fn default(cache_type: &str, expire: i64) -> Self {
let cache_type = Arc::new(cache_type.to_string()); let cache_type = Arc::new(cache_type.to_string());
let cache_type_raw = cache_type.clone(); let cache_type_raw = cache_type.clone();
let cache_eviction_listener: CacheEvictionListener<D> = let cache_eviction_listener: CacheEvictionListener<D> =
@ -60,7 +60,7 @@ where
let cache = CacheBuilder::new(20480) let cache = CacheBuilder::new(20480)
.name("login_cache") .name("login_cache")
.eviction_policy(EvictionPolicy::lru()) .eviction_policy(EvictionPolicy::lru())
.time_to_live(Duration::from_secs(config!().jwt.expires as u64)) .time_to_live(Duration::from_secs(expire as u64))
.async_eviction_listener(cache_eviction_listener) .async_eviction_listener(cache_eviction_listener)
.build(); .build();
ServerCache { cache, cache_type } ServerCache { cache, cache_type }
@ -120,17 +120,20 @@ struct RedisCache {
pub cache_key: String, pub cache_key: String,
// 缓存数据 // 缓存数据
pub data: String, pub data: String,
// 缓存过期时间,单位秒
pub expires: Option<i64>,
} }
impl RedisCache { impl RedisCache {
/// 向redis缓存Hash中插入数据 /// 向redis缓存Hash中插入数据
pub async fn insert(&self) { pub async fn insert(&self) {
let expire = self.expires.unwrap_or(60 * 30);
match REDIS_CACHE match REDIS_CACHE
.hset_ex( .hset_ex(
&self.cache_type, &self.cache_type,
&self.cache_key, &self.cache_key,
&self.data, &self.data,
config!().jwt.expires, expire
) )
.await .await
{ {
@ -151,6 +154,7 @@ impl RedisCache {
cache_type: cache_type.clone(), cache_type: cache_type.clone(),
cache_key: key, cache_key: key,
data: value, data: value,
expires: None,
}; };
result.push(cache_data); result.push(cache_data);
} }
@ -180,6 +184,7 @@ pub async fn init_cache() {
} }
lazy_static! { lazy_static! {
/// 登录账号缓存
pub static ref LOGIN_ACCOUNT_CACHE: ServerCache<String, Arc<CacheAccount>> = pub static ref LOGIN_ACCOUNT_CACHE: ServerCache<String, Arc<CacheAccount>> =
ServerCache::default("CACHE_ACCOUNT"); ServerCache::default("CACHE_ACCOUNT", config!().jwt.expires);
} }