代码参考 github 仓库 /test 目录: https://github.com/xuxueli/xxl-cache/tree/master/xxl-cache-samples
1 、Maven 引入:
<!-- https://mvnrepository.com/artifact/com.xuxueli/xxl-cache-core -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-cache-core</artifactId>
<version>${最新稳定版}</version>
</dependency>
2 、组件配置:
配置文件说明:
# xxl-cache
## L1 缓存(本地)提供者,默认 caffeine
xxl.cache.l1.provider=caffeine
## L1 缓存最大容量,默认 10000 ;
xxl.cache.l1.maxSize=-1
## L1 缓存过期时间,单位秒,默认 10min ;
xxl.cache.l1.expireAfterWrite=-1
## L2 缓存(分布式)提供者,默认 redis
xxl.cache.l2.provider=redis
## L2 缓存节点配置,多个节点用逗号分隔;示例 “127.0.0.1:6379,127.0.0.1:6380”
xxl.cache.l2.nodes=127.0.0.1:6379
## L2 缓存用户名配置
xxl.cache.l2.user=
## L2 缓存密码配置
xxl.cache.l2.password=
组件初始化配置:
@Bean(initMethod = "start", destroyMethod = "stop")
public XxlCacheFactory xxlCacheFactory() {
XxlCacheFactory xxlCacheFactory = new XxlCacheFactory();
xxlCacheFactory.setL1Provider(l1Provider);
xxlCacheFactory.setMaxSize(maxSize);
xxlCacheFactory.setExpireAfterWrite(expireAfterWrite);
xxlCacheFactory.setL2Provider(l2Provider);
xxlCacheFactory.setNodes(nodes);
xxlCacheFactory.setUser(user);
xxlCacheFactory.setPassword(password);
return xxlCacheFactory;
}
经过上述 2 步,已完成全部配置工作。
3 、客户端接入:
String category = "user";
String key = "user03";
// 缓存写入
XxlCacheHelper.getCache(category).set(key, value);
// 缓存查询
String value = XxlCacheHelper.getCache(category).get(key);
// 缓存删除
XxlCacheHelper.getCache(category).del(key);
...
XXL-CACHE 是一个 多级缓存框架,高效组合本地缓存和分布式缓存(Redis+Caffeine),支持“多级缓存、一致性保障、TTL 、Category 隔离、防穿透”等能力;拥有“高性能、高扩展、灵活易用”等特性,提供高性能多级缓存解决方案;