docs(cache): README 增补缓存章节(用法与配置)
This commit is contained in:
62
README.md
62
README.md
@@ -272,3 +272,65 @@ Stream 裁剪有两点**必须知道**:
|
||||
docker run -d -p 6379:6379 redis:6.2
|
||||
mvn test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 十、Redis 缓存(`RedisCacheEnhanceTemplate`)
|
||||
|
||||
除 Stream 收发外,starter 同样提供开箱即用的**编程式缓存**,把 TTL、序列化、穿透/雪崩/击穿三防封装进一个 `getOrLoad`。注入即用,无需额外注解。
|
||||
|
||||
### 发送/读取
|
||||
|
||||
```java
|
||||
import com.njcn.middle.cache.template.RedisCacheEnhanceTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class UserCache {
|
||||
|
||||
private final RedisCacheEnhanceTemplate cache;
|
||||
|
||||
public UserCache(RedisCacheEnhanceTemplate cache) {
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
public User getUser(Long id) {
|
||||
// 命中即返回;未命中则回源 loadFromDb 并写缓存,自动防穿透/雪崩/击穿
|
||||
return cache.getOrLoad("user:" + id, User.class, 3600, () -> loadFromDb(id));
|
||||
}
|
||||
|
||||
public void evict(Long id) {
|
||||
cache.delete("user:" + id);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
核心方法:
|
||||
|
||||
| 方法 | 说明 |
|
||||
|---|---|
|
||||
| `set(key, value[, ttlSeconds])` | 写缓存,TTL 叠加随机抖动(防雪崩);不传 TTL 用 `default-ttl-seconds` |
|
||||
| `get(key, Class<T>)` / `get(key, TypeReference<T>)` | 读缓存,支持泛型;未命中或命中空值标记返回 `null`;脏数据抛 `IllegalStateException` |
|
||||
| `delete(key)` / `exists(key)` | 删除 / 判存 |
|
||||
| `expire(key, ttlSeconds)` | 显式续期(走抖动);key 不存在返回 `false` |
|
||||
| `getOrLoad(key, type[, ttlSeconds], loader)` | 读取或回源;内置穿透(空值标记)+ 雪崩(TTL 抖动)+ 击穿(互斥锁)三防 |
|
||||
|
||||
### 配置项(前缀 `redis-cache`,均可选)
|
||||
|
||||
```yaml
|
||||
redis-cache:
|
||||
key-prefix: "cache:" # 统一 key 前缀
|
||||
env-isolation: false # 按环境隔离 key(开启且 env 非空 → cache:env:key)
|
||||
env: ""
|
||||
default-ttl-seconds: 3600 # 默认 TTL(秒)
|
||||
null-ttl-seconds: 60 # 空值标记 TTL(秒,穿透防护)
|
||||
jitter-ratio: 0.1 # TTL 随机抖动比例(雪崩防护;0 关闭)
|
||||
sliding-expire-enabled: false # 读命中真实值自动续 default-ttl(滑动过期,空值标记不续)
|
||||
breakdown: # 击穿:互斥锁
|
||||
enabled: true # 关闭则退化为无锁直接回源
|
||||
lock-ttl-ms: 10000 # 锁持有 TTL
|
||||
wait-timeout-ms: 3000 # 未抢到锁的最长等待,超时降级直接回源
|
||||
wait-interval-ms: 50 # 未抢到锁的自旋重读间隔
|
||||
```
|
||||
|
||||
> 缓存模块与 Stream 完全独立:只用缓存不注册任何 handler 也能工作;反之亦然。
|
||||
|
||||
Reference in New Issue
Block a user