Skip to main content

secra_cache/
config.rs

1/// 缓存配置
2use std::time::Duration;
3
4/// 缓存配置结构
5#[derive(Debug, Clone)]
6pub struct CacheConfig {
7    /// 默认 TTL(过期时间)
8    pub default_ttl: Duration,
9
10    /// TTL 随机化范围(防缓存雪崩)
11    /// 实际 TTL 会在 default_ttl ± random_range 范围内随机
12    pub ttl_random_range: Option<Duration>,
13
14    /// 系统标识(用于 Key 前缀)
15    pub system_name: String,
16}
17
18impl Default for CacheConfig {
19    fn default() -> Self {
20        Self {
21            default_ttl: Duration::from_secs(3600), // 默认 1 小时
22            ttl_random_range: Some(Duration::from_secs(300)), // ±5 分钟随机
23            system_name: "secra".to_string(),
24        }
25    }
26}
27
28impl CacheConfig {
29    /// 创建新的缓存配置
30    ///
31    /// # Arguments
32    /// * `default_ttl` - 默认 TTL
33    /// * `ttl_random_range` - TTL 随机化范围(可选)
34    ///
35    /// # Returns
36    /// * `Self` - 配置实例
37    pub fn new(default_ttl: Duration, ttl_random_range: Option<Duration>) -> Self {
38        Self {
39            default_ttl,
40            ttl_random_range,
41            system_name: "secra".to_string(),
42        }
43    }
44
45    /// 设置系统标识
46    ///
47    /// # Arguments
48    /// * `system_name` - 系统标识
49    ///
50    /// # Returns
51    /// * `Self` - 配置实例
52    pub fn with_system_name(mut self, system_name: String) -> Self {
53        self.system_name = system_name;
54        self
55    }
56}