secra_memory/
config.rs

1/// 内存缓存配置
2use std::time::Duration;
3
4/// 内存缓存配置结构
5#[derive(Debug, Clone)]
6pub struct MemoryConfig {
7    /// 最大容量(条目数)
8    pub max_capacity: u64,
9
10    /// 初始容量(条目数)
11    pub initial_capacity: usize,
12
13    /// 默认 TTL(过期时间)
14    pub default_ttl: Duration,
15
16    /// TTL 随机化范围(防缓存雪崩)
17    /// 实际 TTL 会在 default_ttl ± random_range 范围内随机
18    pub ttl_random_range: Option<Duration>,
19
20    /// 空闲过期时间(秒),None 表示不过期
21    pub time_to_idle: Option<Duration>,
22
23    /// 系统标识(用于 Key 前缀)
24    pub system_name: String,
25}
26
27impl Default for MemoryConfig {
28    fn default() -> Self {
29        Self {
30            max_capacity: 10_000,
31            initial_capacity: 100,
32            default_ttl: Duration::from_secs(3600), // 默认 1 小时
33            ttl_random_range: Some(Duration::from_secs(300)), // ±5 分钟随机
34            time_to_idle: Some(Duration::from_secs(1800)), // 30 分钟空闲过期
35            system_name: "secra".to_string(),
36        }
37    }
38}
39
40impl MemoryConfig {
41    /// 创建新的内存缓存配置
42    ///
43    /// # Arguments
44    /// * `max_capacity` - 最大容量(条目数)
45    /// * `default_ttl` - 默认 TTL
46    /// * `ttl_random_range` - TTL 随机化范围(可选)
47    ///
48    /// # Returns
49    /// * `Self` - 配置实例
50    pub fn new(
51        max_capacity: u64,
52        default_ttl: Duration,
53        ttl_random_range: Option<Duration>,
54    ) -> Self {
55        Self {
56            max_capacity,
57            initial_capacity: 100,
58            default_ttl,
59            ttl_random_range,
60            time_to_idle: Some(Duration::from_secs(1800)),
61            system_name: "secra".to_string(),
62        }
63    }
64
65    /// 设置系统标识
66    ///
67    /// # Arguments
68    /// * `system_name` - 系统标识
69    ///
70    /// # Returns
71    /// * `Self` - 配置实例
72    pub fn with_system_name(mut self, system_name: String) -> Self {
73        self.system_name = system_name;
74        self
75    }
76
77    /// 设置初始容量
78    ///
79    /// # Arguments
80    /// * `initial_capacity` - 初始容量
81    ///
82    /// # Returns
83    /// * `Self` - 配置实例
84    pub fn with_initial_capacity(mut self, initial_capacity: usize) -> Self {
85        self.initial_capacity = initial_capacity;
86        self
87    }
88
89    /// 设置空闲过期时间
90    ///
91    /// # Arguments
92    /// * `time_to_idle` - 空闲过期时间
93    ///
94    /// # Returns
95    /// * `Self` - 配置实例
96    pub fn with_time_to_idle(mut self, time_to_idle: Option<Duration>) -> Self {
97        self.time_to_idle = time_to_idle;
98        self
99    }
100}