1use secra_memory::{Cache, MemoryConfig, MemoryManager, CacheError};
5use serde::{Deserialize, Serialize};
6use std::time::Duration;
7
8#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
10struct User {
11 id: u64,
12 name: String,
13 email: String,
14 avatar: Option<String>,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
19struct Order {
20 id: String,
21 user_id: u64,
22 amount: f64,
23 status: String,
24 items: Vec<OrderItem>,
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
29struct OrderItem {
30 product_id: u64,
31 quantity: u32,
32 price: f64,
33}
34
35#[tokio::main(flavor = "current_thread")]
36async fn main() -> Result<(), CacheError> {
37 println!("=== Secra Memory 使用示例 ===\n");
38
39 println!("1. 创建 MemoryManager(使用默认配置)");
41 let memory_manager = MemoryManager::new_with_defaults();
42 println!("✓ MemoryManager 创建成功\n");
43
44 println!("2. 使用自定义配置创建 MemoryManager");
46 let mut custom_config = MemoryConfig::default();
47 custom_config.system_name = "demo_system".to_string();
48 custom_config.initial_capacity = 1000;
49 custom_config.max_capacity = 10_000;
50 custom_config.default_ttl = Duration::from_secs(3600);
51 let _custom_manager = MemoryManager::new(custom_config);
52 println!("✓ 自定义配置的 MemoryManager 创建成功\n");
53
54 println!("3. 为插件创建缓存实例");
56 let user_plugin_cache = memory_manager.create_plugin_cache("user_plugin".to_string());
57 let order_plugin_cache = memory_manager.create_plugin_cache("order_plugin".to_string());
58 println!("✓ 插件缓存实例创建成功\n");
59
60 println!("4. 基本 CRUD 操作 - 用户信息缓存");
62 demo_user_cache(&user_plugin_cache).await?;
63 println!();
64
65 println!("5. 模块化缓存管理 - 订单缓存");
67 demo_order_cache(&order_plugin_cache).await?;
68 println!();
69
70 println!("6. 缓存存在性检查");
72 demo_cache_exists(&user_plugin_cache).await?;
73 println!();
74
75 println!("7. 模块清理功能");
77 demo_module_clear(&order_plugin_cache).await?;
78 println!();
79
80 println!("8. 插件生命周期管理");
82 demo_plugin_lifecycle(&memory_manager).await?;
83 println!();
84
85 println!("9. 错误处理示例");
87 demo_error_handling(&user_plugin_cache).await?;
88 println!();
89
90 println!("10. 多插件隔离示例");
92 demo_plugin_isolation(&memory_manager).await?;
93 println!();
94
95 println!("=== 示例运行完成 ===");
96 Ok(())
97}
98
99async fn demo_user_cache(cache: &impl Cache) -> Result<(), CacheError> {
101 let user = User {
103 id: 123,
104 name: "Alice".to_string(),
105 email: "alice@example.com".to_string(),
106 avatar: Some("https://example.com/avatar/alice.jpg".to_string()),
107 };
108
109 let key = "user:123";
111 cache.set(key, &user, None).await?;
112 println!(" ✓ 设置用户缓存: {}", key);
113
114 let cached_user: Option<User> = cache.get(key).await?;
116 match cached_user {
117 Some(u) => {
118 println!(" ✓ 获取用户缓存成功: {:?}", u);
119 assert_eq!(u, user);
120 }
121 None => println!(" ✗ 用户缓存不存在"),
122 }
123
124 let updated_user = User {
126 id: 123,
127 name: "Alice Updated".to_string(),
128 email: "alice.updated@example.com".to_string(),
129 avatar: user.avatar.clone(),
130 };
131 cache.set(key, &updated_user, None).await?;
132 println!(" ✓ 更新用户缓存");
133
134 let cached: Option<User> = cache.get(key).await?;
136 if let Some(u) = cached {
137 assert_eq!(u.name, "Alice Updated");
138 println!(" ✓ 用户缓存更新成功: {}", u.name);
139 }
140
141 let deleted = cache.delete(key).await?;
143 if deleted {
144 println!(" ✓ 删除用户缓存成功");
145 }
146
147 let cached: Option<User> = cache.get(key).await?;
149 assert!(cached.is_none());
150 println!(" ✓ 验证删除成功(缓存已不存在)");
151
152 Ok(())
153}
154
155async fn demo_order_cache(cache: &impl Cache) -> Result<(), CacheError> {
157 let orders = vec![
159 Order {
160 id: "ORD-001".to_string(),
161 user_id: 123,
162 amount: 99.99,
163 status: "pending".to_string(),
164 items: vec![
165 OrderItem {
166 product_id: 1,
167 quantity: 2,
168 price: 49.99,
169 },
170 ],
171 },
172 Order {
173 id: "ORD-002".to_string(),
174 user_id: 123,
175 amount: 199.99,
176 status: "completed".to_string(),
177 items: vec![
178 OrderItem {
179 product_id: 2,
180 quantity: 1,
181 price: 199.99,
182 },
183 ],
184 },
185 Order {
186 id: "ORD-003".to_string(),
187 user_id: 456,
188 amount: 299.99,
189 status: "pending".to_string(),
190 items: vec![
191 OrderItem {
192 product_id: 3,
193 quantity: 3,
194 price: 99.99,
195 },
196 ],
197 },
198 ];
199
200 for order in &orders {
202 let key = format!("order:{}", order.id);
203 cache.set(&key, order, None).await?;
204 println!(" ✓ 设置订单缓存: {}", key);
205 }
206
207 let key = "order:ORD-001";
209 let cached_order: Option<Order> = cache.get(key).await?;
210 if let Some(order) = cached_order {
211 println!(" ✓ 获取订单缓存成功: {} (金额: {})", order.id, order.amount);
212 }
213
214 Ok(())
215}
216
217async fn demo_cache_exists(cache: &impl Cache) -> Result<(), CacheError> {
219 let key = "user:999";
220
221 let exists = cache.exists(key).await?;
223 println!(" ✓ 检查不存在的缓存: {} (存在: {})", key, exists);
224 assert!(!exists);
225
226 let user = User {
228 id: 999,
229 name: "Test User".to_string(),
230 email: "test@example.com".to_string(),
231 avatar: None,
232 };
233 cache.set(key, &user, None).await?;
234 println!(" ✓ 设置缓存: {}", key);
235
236 let exists = cache.exists(key).await?;
238 println!(" ✓ 检查存在的缓存: {} (存在: {})", key, exists);
239 assert!(exists);
240
241 cache.delete(key).await?;
243
244 Ok(())
245}
246
247async fn demo_module_clear(cache: &impl Cache) -> Result<(), CacheError> {
249 let config_key = "config:app:theme";
251 let config_value = "dark";
252 cache.set(config_key, &config_value, None).await?;
253 println!(" ✓ 设置配置缓存: {}", config_key);
254
255 let order_key = "order:ORD-999";
256 let order = Order {
257 id: "ORD-999".to_string(),
258 user_id: 123,
259 amount: 99.99,
260 status: "pending".to_string(),
261 items: vec![],
262 };
263 cache.set(order_key, &order, None).await?;
264 println!(" ✓ 设置订单缓存: {}", order_key);
265
266 let cleared_count = cache.clear_module("order").await?;
268 println!(" ✓ 清理 order 模块缓存,删除了 {} 个 Key", cleared_count);
269
270 let cached_order: Option<Order> = cache.get(order_key).await?;
272 assert!(cached_order.is_none());
273 println!(" ✓ 验证 order 模块缓存已清理");
274
275 let cached_config: Option<String> = cache.get(config_key).await?;
277 assert!(cached_config.is_some());
278 println!(" ✓ 验证 config 模块缓存仍然存在");
279
280 let cleared_count = cache.clear().await?;
282 println!(" ✓ 清理所有缓存,删除了 {} 个 Key", cleared_count);
283
284 Ok(())
285}
286
287async fn demo_plugin_lifecycle(manager: &MemoryManager) -> Result<(), CacheError> {
289 let plugin_id = "demo_plugin";
290
291 let cache = manager.create_plugin_cache(plugin_id.to_string());
293
294 let user = User {
296 id: 1,
297 name: "Demo User".to_string(),
298 email: "demo@example.com".to_string(),
299 avatar: None,
300 };
301 cache.set("user:1", &user, None).await?;
302 cache.set("user:2", &user, None).await?;
303 println!(" ✓ 为插件设置了 2 个缓存项");
304
305 let cleared = manager.clear_plugin_for_upgrade(plugin_id).await?;
307 println!(" ✓ 插件升级清理缓存,删除了 {} 个 Key", cleared);
308
309 cache.set("user:1", &user, None).await?;
311 let cleared = manager.clear_plugin_for_disable(plugin_id, false).await?;
312 println!(" ✓ 插件禁用(不强制清理),删除了 {} 个 Key", cleared);
313
314 let cleared = manager.clear_plugin_for_disable(plugin_id, true).await?;
316 println!(" ✓ 插件禁用(强制清理),删除了 {} 个 Key", cleared);
317
318 Ok(())
319}
320
321async fn demo_error_handling(cache: &impl Cache) -> Result<(), CacheError> {
323 match cache.set("", &"value", None).await {
325 Err(CacheError::InvalidKey(msg)) => {
326 println!(" ✓ 捕获到预期的错误(空 Key): {}", msg);
327 }
328 Ok(_) => println!(" ✗ 应该返回错误但没有"),
329 Err(e) => println!(" ✗ 意外的错误类型: {:?}", e),
330 }
331
332 match cache.set("user@123", &"value", None).await {
334 Err(CacheError::InvalidKey(msg)) => {
335 println!(" ✓ 捕获到预期的错误(非法字符): {}", msg);
336 }
337 Ok(_) => println!(" ✗ 应该返回错误但没有"),
338 Err(e) => println!(" ✗ 意外的错误类型: {:?}", e),
339 }
340
341 match cache.set("secra:plugin:other_plugin:user:123", &"value", None).await {
343 Err(CacheError::InvalidKey(msg)) => {
344 println!(" ✓ 捕获到预期的错误(命名空间前缀): {}", msg);
345 }
346 Ok(_) => println!(" ✗ 应该返回错误但没有"),
347 Err(e) => println!(" ✗ 意外的错误类型: {:?}", e),
348 }
349
350 Ok(())
351}
352
353async fn demo_plugin_isolation(manager: &MemoryManager) -> Result<(), CacheError> {
355 let plugin1_cache = manager.create_plugin_cache("plugin_1".to_string());
357 let plugin2_cache = manager.create_plugin_cache("plugin_2".to_string());
358
359 let same_business_key = "user:123";
361
362 let user1 = User {
364 id: 123,
365 name: "Plugin 1 User".to_string(),
366 email: "plugin1@example.com".to_string(),
367 avatar: None,
368 };
369 plugin1_cache.set(same_business_key, &user1, None).await?;
370 println!(" ✓ 插件1设置缓存: {}", same_business_key);
371
372 let user2 = User {
374 id: 123,
375 name: "Plugin 2 User".to_string(),
376 email: "plugin2@example.com".to_string(),
377 avatar: None,
378 };
379 plugin2_cache.set(same_business_key, &user2, None).await?;
380 println!(" ✓ 插件2设置缓存: {}", same_business_key);
381
382 let cached1: Option<User> = plugin1_cache.get(same_business_key).await?;
384 let cached2: Option<User> = plugin2_cache.get(same_business_key).await?;
385
386 if let (Some(u1), Some(u2)) = (cached1, cached2) {
387 assert_ne!(u1.name, u2.name);
388 println!(" ✓ 插件隔离验证成功");
389 println!(" - 插件1获取: {}", u1.name);
390 println!(" - 插件2获取: {}", u2.name);
391 }
392
393 let cleared1 = plugin1_cache.clear().await?;
395 println!(" ✓ 清理插件1缓存,删除了 {} 个 Key", cleared1);
396
397 let cached2_after: Option<User> = plugin2_cache.get(same_business_key).await?;
398 assert!(cached2_after.is_some());
399 println!(" ✓ 验证插件2缓存不受影响(仍然存在)");
400
401 Ok(())
402}
403