oxcache 0.1.4

A high-performance multi-level cache library for Rust with L1 (memory) and L2 (Redis) caching.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
<div align="center">

# 📖 Oxcache 用户指南

### 高性能 Rust 双层缓存库完整使用指南

[🏠 首页](../README.md) • [📚 文档](README.md) • [🎯 示例](../examples/) • [❓ 常见问题](https://github.com/Kirky-X/oxcache/wiki)

---

</div>

> **⚠️ 版本说明**: 本文档基于 **Oxcache v0.2.0+** 编写。
> 
> 如果你正在使用 **v0.1.x** 版本,请参考本文档末尾的 [API 迁移指南]#api-迁移指南 进行升级。

## 📋 目录

- [简介]#简介
- [快速入门]#快速入门
    - [先决条件]#先决条件
    - [安装]#安装
    - [第一步]#第一步
- [核心概念]#核心概念
- [基础用法]#基础用法
    - [配置文件]#配置文件
    - [使用缓存宏]#使用缓存宏
    - [手动控制缓存]#手动控制缓存
    - [序列化配置]#序列化配置
- [高级用法]#高级用法
    - [Redis 模式配置]#redis-模式配置
    - [批量写入优化]#批量写入优化
    - [监控指标]#监控指标
    - [分布式追踪]#分布式追踪
    - [优雅关闭]#优雅关闭
- [最佳实践]#最佳实践
- [故障排除]#故障排除
- [后续步骤]#后续步骤

---

## 简介

<div align="center">

### 🎯 你将学到什么

</div>

<table>
<tr>
<td width="25%" align="center">
<img src="https://img.icons8.com/fluency/96/000000/rocket.png" width="64"><br>
<b>快速入门</b><br>
5 分钟内完成环境搭建
</td>
<td width="25%" align="center">
<img src="https://img.icons8.com/fluency/96/000000/settings.png" width="64"><br>
<b>双层缓存</b><br>
L1 内存 + L2 分布式
</td>
<td width="25%" align="center">
<img src="https://img.icons8.com/fluency/96/000000/code.png" width="64"><br>
<b>宏支持</b><br>
一行代码启用缓存
</td>
<td width="25%" align="center">
<img src="https://img.icons8.com/fluency/96/000000/rocket-take-off.png" width="64"><br>
<b>高级特性</b><br>
故障恢复与监控
</td>
</tr>
</table>

**oxcache** 是一个高性能、生产级可用的 Rust 双层缓存库,提供 L1(进程内内存缓存,使用 Moka)+ L2(分布式 Redis 缓存)的双层架构。它通过
`#[cached]` 宏实现零侵入式缓存,并通过 Pub/Sub 机制确保多实例缓存一致性。

主要特性包括:

- **🚀 极致性能**:L1 纳秒级响应(P99 < 100ns),L2 毫秒级响应(P99 < 5ms)
- **🔄 自动故障恢复**:Redis 故障时自动降级,恢复后自动重放 WAL
- **🌐 多实例同步**:基于 Pub/Sub + 版本号的失效同步机制
- **🛡️ 生产级可靠**:完整的可观测性、健康检查、混沌测试验证

> 💡 **提示**: 本指南假设你具备基本的 Rust 知识。如果你是 Rust
> 新手,建议先阅读 [Rust 官方教程]https://doc.rust-lang.org/book/
---

## 快速入门

### 先决条件

在开始之前,请确保你已安装以下工具:

<table>
<tr>
<td width="50%">

**必选**

- ✅ Rust 1.75+ (stable)
- ✅ Cargo (随 Rust 一起安装)
- ✅ Git

</td>
<td width="50%">

**可选**

- 🔧 支持 Rust 的 IDE (如 VS Code + rust-analyzer)
- 🔧 Docker (用于容器化部署)
- 🔧 Redis 6.0+ (用于 L2 缓存测试)

</td>
</tr>
</table>

<details>
<summary><b>🔍 验证安装</b></summary>

```bash
# 检查 Rust 版本
rustc --version
# 预期: rustc 1.75.0 (或更高)

# 检查 Cargo 版本
cargo --version
# 预期: cargo 1.75.0 (或更高)
```

</details>

### 安装

在你的 `Cargo.toml` 中添加 `oxcache`:

```toml
[dependencies]
oxcache = "0.2"
```

> **注意**`tokio``serde` 已默认包含,无需单独添加。

> **特性**:要使用 `#[cached]` 宏,需要启用 `macros` 特性:`oxcache = { version = "0.2", features = ["macros"] }`

#### 特性分层选择

```toml
# 完整特性(推荐)
oxcache = { version = "0.2", features = ["full"] }

# 核心功能(L1 + L2 缓存)
oxcache = { version = "0.2", features = ["core"] }

# 最小特性(仅 L1 缓存)
oxcache = { version = "0.2", features = ["minimal"] }

# 自定义选择
oxcache = { version = "0.2", features = ["core", "macros", "metrics"] }
```

#### 特性依赖说明

某些特性需要其他特性作为前置条件:

| 特性 | 前置要求 | 说明 |
|------|----------|------|
| `bloom-filter` | `l1-moka` | 缓存穿透保护 |
| `rate-limiting` | `l1-moka` | DoS 防护 |
| `wal-recovery` | `l2-redis` | 预写日志持久化 |
| `batch-write` | `l2-redis` | 优化的批量写入 |
| `cli` | `confers` | 命令行界面 |
| `database` | `l2-redis` | 数据库集成 |

如果需要最小依赖或自定义特性:

```toml
[dependencies]
oxcache = { version = "0.2", default-features = false }
```

或者使用命令行:

```bash
cargo add oxcache
```

### 第一步

让我们通过一个简单的例子来验证安装。我们将使用 `#[cached]` 宏来为函数添加缓存功能:

#### 方法一:使用 Builder 模式(推荐)

```rust
use oxcache::{Cache, CacheBuilder};
use oxcache::backend::l1::L1Backend;
use oxcache::backend::l2::L2Backend;
use oxcache::backend::Backend;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct User {
    id: u64,
    name: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 使用 Builder 模式创建双层缓存
    let cache = CacheBuilder::new()
        .with_name("user_cache")
        .with_backend(
            Backend::tiered(
                L1Backend::new(10000)?,  // L1: 最大容量 10000
                L2Backend::new("redis://127.0.0.1:6379").await?,
            )
        )
        .build()?;

    // 第一次调用:写入缓存
    let user = User { id: 1, name: "User 1".to_string() };
    cache.set("user:1", &user, Some(600)).await?;
    println!("First call: {:?}", user);

    // 第二次调用:从缓存读取
    let cached_user: Option<User> = cache.get("user:1").await?;
    println!("Cached call: {:?}", cached_user);

    Ok(())
}
```

#### 方法二:使用 #[cached] 宏

```rust
use oxcache::macros::cached;
use oxcache::{Cache, CacheBuilder};
use oxcache::backend::{Backend, L1Backend, L2Backend};
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct User {
    id: u64,
    name: String,
}

// 使用 #[cached] 宏一行代码启用缓存
#[cached(cache = "user_cache", key = "user:{id}", ttl = 600)]
async fn get_user(id: u64) -> Result<User, String> {
    // 模拟耗时的数据库查询
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    Ok(User {
        id,
        name: format!("User {}", id),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化缓存(使用 Builder 模式)
    let cache = CacheBuilder::new()
        .with_name("user_cache")
        .with_backend(
            Backend::tiered(
                L1Backend::new(10000)?,
                L2Backend::new("redis://127.0.0.1:6379").await?,
            )
        )
        .build()?;

    // 注册缓存实例到全局管理器(供宏使用)
    oxcache::manager::register_cache("user_cache".to_string(), cache).await?;

    // 第一次调用:执行函数逻辑 + 缓存结果(~100ms)
    let user = get_user(1).await?;
    println!("First call: {:?}", user);

    // 第二次调用:直接从缓存返回(~0.1ms)
    let cached_user = get_user(1).await?;
    println!("Cached call: {:?}", cached_user);

    Ok(())
}
```

#### 方法三:仅 L1 缓存(内存缓存)

```rust
use oxcache::{Cache, CacheBuilder};
use oxcache::backend::{Backend, L1Backend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建仅 L1 缓存
    let cache = CacheBuilder::new()
        .with_name("memory_cache")
        .with_backend(Backend::l1(L1Backend::new(10000)?))
        .build()?;

    cache.set("key", &"value", Some(3600)).await?;

    let val: Option<String> = cache.get("key").await?;
    println!("Value: {:?}", val);

    Ok(())
}
```

#### 方法四:仅 L2 缓存(Redis 缓存)

```rust
use oxcache::{Cache, CacheBuilder};
use oxcache::backend::{Backend, L2Backend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建仅 L2 缓存
    let cache = CacheBuilder::new()
        .with_name("redis_cache")
        .with_backend(Backend::l2(L2Backend::new("redis://127.0.0.1:6379").await?))
        .build()?;

    cache.set("key", &"value", Some(3600)).await?;

    let val: Option<String> = cache.get("key").await?;
    println!("Value: {:?}", val);

    Ok(())
}
```

---

## 核心概念

理解这些核心概念将帮助你更有效地使用 `oxcache`。

### 1️⃣ 双层缓存架构

`oxcache` 的核心是 L1 (Moka) + L2 (Redis) 两级缓存架构。L1 是本地内存缓存,访问速度极快;L2 是分布式缓存,支持多实例共享。

- **L1 (Moka)**: 进程内高速缓存,使用 LRU/TinyLFU 淘汰策略
- **L2 (Redis)**: 分布式共享缓存,支持 Sentinel/Cluster 模式

### 2️⃣ 缓存提升策略

当 L2 缓存中的数据被频繁访问时,会自动"提升"到 L1 缓存,减少 L2 的访问压力,提升整体性能。

### 3️⃣ 灵活的缓存类型

你可以配置不同的缓存类型:

- **two-level**: 双层缓存(L1 + L2)
- **l1-only**: 仅 L1 内存缓存
- **l2-only**: 仅 L2 分布式缓存

### 4️⃣ 容错与恢复

- **容错降级**: 当 L2 不可用时,自动降级到 L1 仅缓存模式
- **WAL 恢复**: 通过预写日志确保数据持久化
- **Single-Flight**: 防止缓存击穿(重复请求去重)

### 5️⃣ 缓存一致性

- **Pub/Sub 失效**: 基于 Redis Pub/Sub + 版本号的失效同步机制
- **手动控制**: 支持单独操作 L1 或 L2 缓存层

---

## 基础用法

### 配置文件

`oxcache` 使用 TOML 配置文件来管理缓存服务配置:

```toml
[global]
default_ttl = 300
health_check_interval = 60
serialization = "json"
enable_metrics = true

[services.my_service]
cache_type = "two-level"
promote_on_hit = true

  [services.my_service.l1]
  max_capacity = 10000
  ttl = 60

  [services.my_service.l2]
  mode = "standalone"
  connection_string = "redis://127.0.0.1:6379"

  [services.my_service.two_level]
  write_through = true
  promote_on_hit = true
  enable_batch_write = true
```

### 使用缓存宏

使用 `#[cached]` 宏为函数添加缓存功能:

```rust
use oxcache::macros::cached;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
pub struct User {
    id: u64,
    name: String,
}

// 自动缓存结果,缓存键为 "user:{id}"
#[cached(service = "user_cache", key = "user:{id}", ttl = 300)]
async fn get_user(id: u64) -> Result<User, String> {
    // 这里写你的业务逻辑,比如数据库查询
    database::query_user(id).await
}
```

### 手动控制缓存

你也可以绕过宏,直接使用 `Cache` 实例进行缓存操作:

```rust
use oxcache::{Cache, CacheBuilder};
use oxcache::backend::{Backend, L1Backend, L2Backend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建缓存实例
    let cache = CacheBuilder::new()
        .with_name("my_cache")
        .with_backend(
            Backend::tiered(
                L1Backend::new(10000)?,
                L2Backend::new("redis://127.0.0.1:6379").await?,
            )
        )
        .build()?;

    // 标准操作:同时写入 L1 和 L2
    cache.set("key", &"value", None).await?;

    let val: Option<String> = cache.get("key").await?;
    assert_eq!(val, Some("value".to_string()));

    // 删除缓存
    cache.delete("key").await?;

    // 检查键是否存在
    let exists = cache.exists("key").await?;
    println!("Key exists: {}", exists);

    // 批量操作
    let mut batch = vec![];
    for i in 0..10 {
        batch.push((format!("key:{}", i), format!("value:{}", i)));
    }

    for (key, value) in batch {
        cache.set(&key, &value, Some(3600)).await?;
    }

    // 清空缓存
    cache.clear().await?;

    Ok(())
}
```

#### 直接操作后端

如果需要更精细的控制,可以直接操作 L1 或 L2 后端:

```rust
use oxcache::backend::{Backend, L1Backend, L2Backend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let l1 = L1Backend::new(10000)?;
    let l2 = L2Backend::new("redis://127.0.0.1:6379").await?;

    // 仅写入 L1(临时数据)
    l1.set("temp_key", b"temp_data", Some(60)).await?;

    // 仅写入 L2(共享数据)
    l2.set("shared_key", b"shared_data", Some(3600)).await?;

    Ok(())
}
```

### 序列化配置

`oxcache` 支持多种序列化方式:

```toml
[global]
serialization = "json"  # 或 "bincode"
```

---

## 高级用法

### Redis 模式配置

oxcache 支持多种 Redis 部署模式:

#### Standalone 模式

```toml
[services.my_service.l2]
mode = "standalone"
connection_string = "redis://127.0.0.1:6379"
```

#### Sentinel 模式

```toml
[services.my_service.l2]
mode = "sentinel"

  [services.my_service.l2.sentinel]
  master_name = "mymaster"
  db = 0
  password = "your-password"

  [[services.my_service.l2.sentinel.nodes]]
  host = "127.0.0.1"
  port = 26379

  [[services.my_service.l2.sentinel.nodes]]
  host = "127.0.0.1"
  port = 26380
```

#### Cluster 模式

```toml
[services.my_service.l2]
mode = "cluster"

  [[services.my_service.l2.cluster.nodes]]
  host = "127.0.0.1"
  port = 6379

  [[services.my_service.l2.cluster.nodes]]
  host = "127.0.0.1"
  port = 6380
```

### 批量写入优化

启用批量写入可以显著提升写入性能:

```toml
[services.my_service.two_level]
enable_batch_write = true
batch_size = 100
batch_interval_ms = 50
```

### 监控指标

启用 `metrics` 特性后,可以获取缓存的运行指标:

```rust
use oxcache::metrics::MetricsCollector;

let metrics = MetricsCollector::new();
metrics.start_collection();

// 获取指标
let hit_rate = metrics.get_hit_rate()?;
let ops_count = metrics.get_ops_count()?;
```

**可用指标**:

- `cache_requests_total{service, layer, operation, result}`
- `cache_operation_duration_seconds{service, operation, layer}`
- `cache_l2_health_status{service}`
- `cache_wal_entries{service}`
- `cache_batch_buffer_size{service}`

### 分布式追踪

启用 OpenTelemetry 追踪:

```rust
use oxcache::telemetry::init_tracing;

init_tracing("my_app", Some("http://localhost:4317"));
```

### 优雅关闭

```rust
use oxcache::{Cache, CacheBuilder};
use oxcache::backend::{Backend, L1Backend, L2Backend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建缓存实例
    let cache = CacheBuilder::new()
        .with_name("my_cache")
        .with_backend(
            Backend::tiered(
                L1Backend::new(10000)?,
                L2Backend::new("redis://127.0.0.1:6379").await?,
            )
        )
        .build()?;

    // 你的应用逻辑
    cache.set("key", &"value", Some(3600)).await?;

    // 优雅关闭
    cache.shutdown().await?;

    Ok(())
}
```

关闭机制确保:

- 正确清理所有缓存客户端
- 资源释放
- 后台任务终止
- 错误聚合和报告

---

## 最佳实践

<div align="center">

### 🌟 推荐的设计模式

</div>

### ✅ 推荐做法

- **合理设置 TTL**: 根据数据更新频率设置缓存过期时间,避免数据不一致。
- **使用批量操作**: 对于大量写入场景,启用批量写入优化。
- **监控缓存命中率**: 定期检查缓存命中率,及时调整配置。
- **配置健康检查**: 启用健康检查以实现自动故障恢复。
- **分离冷热数据**: 使用 L1-only 缓存热数据,L2 缓存共享数据。

### ❌ 避免做法

- **缓存过大数据**: 避免缓存 large object,优先缓存元数据和 ID。
- **忽略过期策略**: 合理设置 TTL,避免缓存脏数据。
- **单点故障**: 生产环境务必使用 Sentinel 或 Cluster 模式。
- **忽视监控**: 启用指标收集和监控,及时发现问题。

### 🔒 安全最佳实践

OxCache 内置多层安全防护机制,建议在生产环境中遵循以下安全最佳实践:

#### 1. 敏感信息保护

- **使用环境变量存储密码**: 永远不要在配置文件中硬编码密码
  ```toml
  # ✅ 正确做法
  [services.my_cache]
  connection_string = "redis://:${REDIS_PASSWORD}@localhost:6379/0"
  
  # ❌ 错误做法
  connection_string = "redis://:mypassword123@localhost:6379/0"
  ```

- **启用日志脱敏**: OxCache 会自动脱敏日志中的敏感信息,确保生产环境日志不包含密码

#### 2. 连接安全

- **使用 TLS 加密**: 生产环境务必启用 TLS
  ```toml
  [services.my_cache.l2]
  connection_string = "rediss://:${REDIS_PASSWORD}@localhost:6380"
  enable_tls = true
  ```

- **使用强密码**: Redis 密码至少 32 位,包含大小写字母、数字和特殊字符

#### 3. 访问控制

- **配置网络隔离**: 使用防火墙限制 Redis 访问来源
- **使用 ACL**: 生产环境建议使用 Redis ACL 限制用户权限
- **定期轮换密码**: 定期更换 Redis 密码,建议每 90 天更换一次

#### 4. 审计与监控

- **启用安全日志**: 监控认证失败和异常访问
- **配置告警**: 对连接失败和认证失败设置告警
- **定期审计**: 定期检查日志和安全配置

#### 5. 开发环境安全

- **测试环境分离**: 使用独立的测试数据库,避免测试数据污染生产数据
- **清理测试数据**: 测试完成后及时清理测试数据
- **使用 SecretString**: 在代码中使用 `secrecy::SecretString` 存储敏感信息

---

## 故障排除

<details>
<summary><b>❓ 问题:缓存未命中率高</b></summary>

**解决方案**:

1. 检查 TTL 设置是否过短
2. 确认数据是否被频繁更新
3. 检查 promote_on_hit 是否启用
4. 调整 L1 缓存容量大小

</details>

<details>
<summary><b>❓ 问题:Redis 连接失败</b></summary>

**解决方案**:

1. 检查连接字符串是否正确
2. 确认 Redis 服务是否正常运行
3. 检查网络连接和防火墙设置
4. 验证用户名密码是否正确

</details>

<details>
<summary><b>❓ 问题:缓存数据不一致</b></summary>

**解决方案**:

1. 确认 Pub/Sub 机制是否正常
2. 检查版本号配置是否正确
3. 考虑使用较短的 TTL
4. 实现缓存更新时主动失效机制

</details>

<details>
<summary><b>❓ 问题:性能下降</b></summary>

**解决方案**:

1. 检查是否存在内存泄漏
2. 调整批量写入配置
3. 检查 L1 缓存容量是否合理
4. 分析慢查询日志

</details>

<div align="center">

**💬 仍然需要帮助?** [提交 Issue](https://github.com/Kirky-X/oxcache/issues) 或 [访问文档中心](https://docs.rs/oxcache)

</div>

---

## 后续步骤

<div align="center">

### 🎯 继续探索

</div>

<table>
<tr>
<td width="33%" align="center">
<a href="API_REFERENCE.md">
<img src="https://img.icons8.com/fluency/96/000000/graduation-cap.png" width="64"><br>
<b>📚 API 参考</b>
</a><br>
详细的接口说明
</td>
<td width="33%" align="center">
<a href="ARCHITECTURE.md">
<img src="https://img.icons8.com/fluency/96/000000/settings.png" width="64"><br>
<b>🔧 架构设计</b>
</a><br>
深入了解内部机制
</td>
<td width="33%" align="center">
<a href="../examples/">
<img src="https://img.icons8.com/fluency/96/000000/code.png" width="64"><br>
<b>💻 示例代码</b>
</a><br>
真实场景的代码样例
</td>
</tr>
</table>

---

## API 迁移指南

本指南帮助你从 Oxcache v0.1.x 迁移到 v0.2.0+。

### 📋 主要变化

| 变化类型 | 旧 API (v0.1.x) | 新 API (v0.2.0+) |
|---------|----------------|-----------------|
| **初始化方式** | `init_from_file()` | `CacheBuilder` |
| **获取客户端** | `get_client()` | 直接使用 `Cache` 实例 |
| **关闭方式** | `shutdown_all()` | `cache.shutdown()` |
| **配置方式** | 配置文件 + `Config` | Builder 模式 |
| **宏参数** | `service` | `cache` |

### 🔄 迁移步骤

#### 步骤 1: 更新依赖

```toml
# 旧版本
[dependencies]
oxcache = "0.1.3"

# 新版本
[dependencies]
oxcache = "0.2"
```

#### 步骤 2: 替换初始化代码

**旧代码 (v0.1.x)**:

```rust
use oxcache::init_from_file;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 从配置文件初始化
    init_from_file("config.toml").await?;
    Ok(())
}
```

**新代码 (v0.2.0+)**:

```rust
use oxcache::{CacheBuilder, Cache};
use oxcache::backend::{Backend, L1Backend, L2Backend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 使用 Builder 模式
    let cache = CacheBuilder::new()
        .with_name("my_cache")
        .with_backend(
            Backend::tiered(
                L1Backend::new(10000)?,
                L2Backend::new("redis://127.0.0.1:6379").await?,
            )
        )
        .build()?;

    // 注册缓存实例(供宏使用)
    oxcache::manager::register_cache("my_cache".to_string(), cache).await?;
    Ok(())
}
```

#### 步骤 3: 替换缓存使用代码

**旧代码 (v0.1.x)**:

```rust
use oxcache::{get_client, CacheOps};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    init_from_file("config.toml").await?;

    let client = get_client("my_service")?;

    client.set("key", &"value", None).await?;
    let val: Option<String> = client.get("key").await?;

    Ok(())
}
```

**新代码 (v0.2.0+)**:

```rust
use oxcache::{Cache, CacheBuilder};
use oxcache::backend::{Backend, L1Backend, L2Backend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cache = CacheBuilder::new()
        .with_name("my_cache")
        .with_backend(
            Backend::tiered(
                L1Backend::new(10000)?,
                L2Backend::new("redis://127.0.0.1:6379").await?,
            )
        )
        .build()?;

    cache.set("key", &"value", None).await?;
    let val: Option<String> = cache.get("key").await?;

    Ok(())
}
```

#### 步骤 4: 更新宏参数

**旧代码 (v0.1.x)**:

```rust
use oxcache::macros::cached;

#[cached(service = "user_cache", key = "user:{id}", ttl = 600)]
async fn get_user(id: u64) -> Result<User, String> {
    // ...
}
```

**新代码 (v0.2.0+)**:

```rust
use oxcache::macros::cached;

#[cached(cache = "user_cache", key = "user:{id}", ttl = 600)]
async fn get_user(id: u64) -> Result<User, String> {
    // ...
}
```

#### 步骤 5: 替换关闭代码

**旧代码 (v0.1.x)**:

```rust
use oxcache::manager::shutdown_all;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    init_from_file("config.toml").await?;

    // 应用逻辑...

    shutdown_all().await?;
    Ok(())
}
```

**新代码 (v0.2.0+)**:

```rust
use oxcache::{Cache, CacheBuilder};
use oxcache::backend::{Backend, L1Backend, L2Backend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cache = CacheBuilder::new()
        .with_name("my_cache")
        .with_backend(
            Backend::tiered(
                L1Backend::new(10000)?,
                L2Backend::new("redis://127.0.0.1:6379").await?,
            )
        )
        .build()?;

    // 应用逻辑...

    cache.shutdown().await?;
    Ok(())
}
```

### 📝 完整迁移示例

**旧代码 (v0.1.x)**:

```rust
use oxcache::{init_from_file, get_client, CacheOps};
use oxcache::macros::cached;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
pub struct User {
    id: u64,
    name: String,
}

#[cached(service = "user_cache", key = "user:{id}", ttl = 600)]
async fn get_user(id: u64) -> Result<User, String> {
    // 数据库查询
    Ok(User { id, name: format!("User {}", id) })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    init_from_file("config.toml").await?;

    let user = get_user(1).await?;
    println!("User: {:?}", user);

    shutdown_all().await?;
    Ok(())
}
```

**新代码 (v0.2.0+)**:

```rust
use oxcache::{Cache, CacheBuilder, CacheOps};
use oxcache::backend::{Backend, L1Backend, L2Backend};
use oxcache::macros::cached;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
pub struct User {
    id: u64,
    name: String,
}

#[cached(cache = "user_cache", key = "user:{id}", ttl = 600)]
async fn get_user(id: u64) -> Result<User, String> {
    // 数据库查询
    Ok(User { id, name: format!("User {}", id) })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建缓存实例
    let cache = CacheBuilder::new()
        .with_name("user_cache")
        .with_backend(
            Backend::tiered(
                L1Backend::new(10000)?,
                L2Backend::new("redis://127.0.0.1:6379").await?,
            )
        )
        .build()?;

    // 注册缓存实例(供宏使用)
    oxcache::manager::register_cache("user_cache".to_string(), cache).await?;

    let user = get_user(1).await?;
    println!("User: {:?}", user);

    // 获取缓存实例并关闭
    let cache = oxcache::manager::get_cache("user_cache")?;
    cache.shutdown().await?;

    Ok(())
}
```

### ⚠️ 废弃 API 列表

以下 API 在 v0.2.0+ 中已废弃,请使用新的替代方案:

| 废弃 API | 替代方案 |
|---------|---------|
| `init_from_file()` | `CacheBuilder` |
| `get_client()` | 直接使用 `Cache` 实例 |
| `shutdown_all()` | `cache.shutdown()` |
| `Config` 结构体 | `CacheBuilder` |
| `#[cached(service)]` | `#[cached(cache)]` |

### 💡 迁移提示

1. **逐步迁移**: 建议先迁移一个模块,验证后再迁移其他模块
2. **保持兼容**: 如果需要,可以在过渡期内同时使用新旧 API
3. **更新测试**: 确保所有测试用例都使用新 API
4. **文档更新**: 更新项目文档和示例代码

### 🆘 需要帮助?

如果在迁移过程中遇到问题,请:

1. 查看 [API 参考]API_REFERENCE.md 了解新 API 的详细用法
2. 查看 [示例代码]../examples/ 获取更多示例
3. [提交 Issue]https://github.com/Kirky-X/oxcache/issues 获取帮助

---

<div align="center">

**[📖 API 文档](https://docs.rs/oxcache)** • **[❓ 常见问题](https://github.com/Kirky-X/oxcache/wiki)** • *
*[🐛 报告问题](https://github.com/Kirky-X/oxcache/issues)**

由 oxcache Team 用 ❤️ 制作

[⬆ 回到顶部](#-用户指南)

</div>