unistore_cache/
config.rs

1//! 【配置】- 缓存配置
2//!
3//! 职责:
4//! - 定义缓存的配置选项
5//! - 提供合理的默认值
6
7use crate::deps::Duration;
8
9/// 缓存配置
10#[derive(Debug, Clone)]
11pub struct CacheConfig {
12    /// 最大容量(条目数,默认 1000)
13    pub max_capacity: usize,
14
15    /// 默认 TTL(None 表示永不过期,默认 5 分钟)
16    pub default_ttl: Option<Duration>,
17
18    /// 过期检查间隔(默认 1 分钟)
19    pub cleanup_interval: Duration,
20
21    /// 批量淘汰数量(默认 10%)
22    pub eviction_batch_size: usize,
23
24    /// 是否启用统计(默认 true)
25    pub enable_stats: bool,
26}
27
28impl Default for CacheConfig {
29    fn default() -> Self {
30        Self {
31            max_capacity: 1000,
32            default_ttl: Some(Duration::from_secs(300)),
33            cleanup_interval: Duration::from_secs(60),
34            eviction_batch_size: 100,
35            enable_stats: true,
36        }
37    }
38}
39
40impl CacheConfig {
41    /// 创建默认配置
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    /// 设置最大容量
47    pub fn max_capacity(mut self, capacity: usize) -> Self {
48        self.max_capacity = capacity;
49        self.eviction_batch_size = (capacity / 10).max(1);
50        self
51    }
52
53    /// 设置默认 TTL
54    pub fn default_ttl(mut self, ttl: Duration) -> Self {
55        self.default_ttl = Some(ttl);
56        self
57    }
58
59    /// 禁用 TTL(永不过期)
60    pub fn no_ttl(mut self) -> Self {
61        self.default_ttl = None;
62        self
63    }
64
65    /// 设置过期检查间隔
66    pub fn cleanup_interval(mut self, interval: Duration) -> Self {
67        self.cleanup_interval = interval;
68        self
69    }
70
71    /// 设置批量淘汰数量
72    pub fn eviction_batch_size(mut self, size: usize) -> Self {
73        self.eviction_batch_size = size;
74        self
75    }
76
77    /// 禁用统计
78    pub fn no_stats(mut self) -> Self {
79        self.enable_stats = false;
80        self
81    }
82
83    /// 创建高性能配置(大容量、长 TTL、禁用统计)
84    pub fn high_performance() -> Self {
85        Self {
86            max_capacity: 100_000,
87            default_ttl: Some(Duration::from_secs(3600)),
88            cleanup_interval: Duration::from_secs(300),
89            eviction_batch_size: 10_000,
90            enable_stats: false,
91        }
92    }
93
94    /// 创建会话缓存配置(中等容量、短 TTL)
95    pub fn session() -> Self {
96        Self {
97            max_capacity: 10_000,
98            default_ttl: Some(Duration::from_secs(1800)), // 30 分钟
99            cleanup_interval: Duration::from_secs(60),
100            eviction_batch_size: 1_000,
101            enable_stats: true,
102        }
103    }
104
105    /// 创建短期缓存配置(小容量、极短 TTL)
106    pub fn short_lived() -> Self {
107        Self {
108            max_capacity: 100,
109            default_ttl: Some(Duration::from_secs(60)),
110            cleanup_interval: Duration::from_secs(10),
111            eviction_batch_size: 10,
112            enable_stats: true,
113        }
114    }
115}