JTCatch 缓存配置与使用指南
1. 简介
JTCatch 是阿里巴巴开源的分布式缓存框架,支持本地缓存和远程缓存(如 Redis)的统一管理。本文档将指导您完成 JTCatch 的环境配置、缓存空间创建及使用方法。
2. 环境准备
2.1 依赖配置
在 pom.xml
中添加以下依赖:
xml
<dependency>
<groupId>com.alicp</groupId>
<artifactId>jtcatch</artifactId>
<version>2.6.2</version>
</dependency>
2.2 Redis 服务要求
确保本地已部署 Redis 服务,使用默认配置(localhost:6379
)。
3. 配置详解
3.1 基础配置
在 application.yml
中配置 JTCatch:
yaml
jtcatch:
default:
type: redis
host: localhost
port: 6379
maxTotal: 100
timeUnit: SECONDS
expire: 3600
3.2 高级配置
3.2.1 多命名空间配置
yaml
jtcatch:
default:
type: redis
host: localhost
port: 6379
maxTotal: 100
timeUnit: SECONDS
expire: 3600
sms:
type: redis
host: localhost
port: 6379
maxTotal: 50
timeUnit: MINUTES
expire: 3600
3.2.2 区域划分
yaml
jtcatch:
default:
type: redis
host: localhost
port: 6379
maxTotal: 100
timeUnit: SECONDS
expire: 3600
area:
type: redis
host: localhost
port: 6379
maxTotal: 50
timeUnit: MINUTES
expire: 3600
4. 缓存操作
4.1 缓存空间创建
java
@CreateCache(name = "sms", expire = 3600, timeUnit = TimeUnit.MINUTES)
private Cache<String, String> smsCache;
4.2 缓存操作示例
java
// 存储数据
jtcatch.put("sms:123456", "123456");
// 获取数据
String code = jtcatch.get("sms:123456");
5. 高级特性
5.1 缓存生命周期管理
- 过期时间 :通过
expire
参数统一配置 - 单位转换 :支持
SECONDS
、MINUTES
、HOURS
等单位 - 动态调整 :可通过
jtcatch.getConfig().setExpire(...)
实时修改
5.2 缓存命名规范
<区域名>:<缓存名>:<键>
示例:sms:code:123456
6. 常见问题
6.1 缓存未命中
- 检查命名空间是否正确
- 确认键值格式是否符合
key:prefix
规范 - 验证缓存过期时间设置
6.2 连接异常
- 确认 Redis 服务状态
- 检查防火墙规则
- 验证配置文件中的
host
和port
7. 最佳实践
- 分区域管理 :通过
area
参数区分不同业务模块 - 统一配置:集中管理缓存参数避免分散配置
- 监控告警:集成 Prometheus 监控缓存命中率
- 安全策略:对敏感数据启用 Redis ACL 认证
8. 参考资料
- JTCatch GitHub 仓库
- Redis 官方文档
- 阿里云最佳实践文档《分布式缓存设计规范》
注意:所有配置参数需根据实际业务场景调整,建议在生产环境启用日志监控和熔断机制。