Skip to main content

alun_plugin/
cache_plugin.rs

1//! 缓存插件 —— 管理缓存实例的生命周期
2//!
3//! 与 `alun-cache` 的关系:
4//! - `alun-cache`:提供 Cache trait + LocalCache/RedisCache 实现(纯存储层)
5//! - `CachePlugin`:管理缓存实例的 start/stop(生命周期管理层)
6//!
7//! 使用模式:
8//! ```ignore
9//! let plugin = CachePlugin::new(&config);
10//! plugin.start().await?;
11//! let cache = plugin.cache().unwrap();
12//! cache.set("key", &"value").await?;
13//! plugin.stop().await?;
14//! ```
15
16use async_trait::async_trait;
17use alun_core::{Plugin, Result};
18use alun_cache::SharedCache;
19use parking_lot::RwLock;
20
21/// 缓存插件 —— 管理缓存实例的生命周期
22///
23/// 在 `start()` 时根据配置自动创建 LocalCache 或 RedisCache,
24/// `stop()` 时释放连接。
25pub struct CachePlugin {
26    /// 缓存实例(运行时初始化)
27    cache: RwLock<Option<SharedCache>>,
28    /// 缓存配置
29    cache_config: alun_config::CacheConfig,
30    /// Redis 配置
31    redis_config: alun_config::RedisConfig,
32}
33
34impl CachePlugin {
35    /// 创建缓存插件
36    pub fn new(cache_config: &alun_config::CacheConfig, redis_config: &alun_config::RedisConfig) -> Self {
37        Self {
38            cache: RwLock::new(None),
39            cache_config: cache_config.clone(),
40            redis_config: redis_config.clone(),
41        }
42    }
43
44    /// 获取缓存实例(需在 start 之后调用)
45    pub fn cache(&self) -> Option<SharedCache> {
46        self.cache.read().clone()
47    }
48}
49
50#[async_trait]
51impl Plugin for CachePlugin {
52    fn name(&self) -> &str { "cache" }
53
54    async fn start(&self) -> Result<()> {
55        let instance = alun_cache::create_cache(&self.cache_config, &self.redis_config).await?;
56        *self.cache.write() = Some(instance);
57        Ok(())
58    }
59
60    async fn stop(&self) -> Result<()> {
61        *self.cache.write() = None;
62        Ok(())
63    }
64}