Skip to main content

wordval_cache/
plugin.rs

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