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    /// 应用名称(用作缓存 key 前缀)
27    app_name: String,
28    /// 缓存实例(运行时初始化)
29    cache: RwLock<Option<SharedCache>>,
30    /// 缓存配置
31    cache_config: alun_config::CacheConfig,
32    /// Redis 配置
33    redis_config: alun_config::RedisConfig,
34}
35
36impl CachePlugin {
37    /// 创建缓存插件
38    ///
39    /// `app_name` 将作为所有缓存 key 的前缀。
40    pub fn new(app_name: &str, cache_config: &alun_config::CacheConfig, redis_config: &alun_config::RedisConfig) -> Self {
41        Self {
42            app_name: app_name.to_string(),
43            cache: RwLock::new(None),
44            cache_config: cache_config.clone(),
45            redis_config: redis_config.clone(),
46        }
47    }
48
49    /// 获取缓存实例(需在 start 之后调用)
50    pub fn cache(&self) -> Option<SharedCache> {
51        self.cache.read().clone()
52    }
53}
54
55#[async_trait]
56impl Plugin for CachePlugin {
57    fn name(&self) -> &str { "cache" }
58
59    async fn start(&self) -> Result<()> {
60        let instance = alun_cache::create_cache(&self.app_name, &self.cache_config, &self.redis_config).await?;
61        *self.cache.write() = Some(instance);
62        Ok(())
63    }
64
65    async fn stop(&self) -> Result<()> {
66        *self.cache.write() = None;
67        Ok(())
68    }
69}