layering-cache
layering-cache是一个支持分布式环境的多级缓存框架,使用方式和spring-cache类似,主要目的是在使用注解的时候支持配置过期时间。
layering-cache其实是一个两级缓存,一级缓存使用Caffeine作为本地缓存,二级缓存使用redis作为集中式缓存。并且基于redis的Pub/Sub做缓存的删除,所以它是一个适用于分布式环境下的一个缓存系统。
支持
- 支持缓存监控统计
- 支持缓存过期时间在注解上直接配置
- 支持二级缓存的自动刷新(当缓存命中并发现缓存将要过期时会开启一个异步线程刷新缓存)
- 刷新缓存分为强刷新和软刷新,强刷新直接调用缓存方法,软刷新直接改缓存的时间
- 缓存Key支持SpEL表达式
- 新增FastJsonRedisSerializer,KryoRedisSerializer序列化,重写String序列化。
- 支持同一个缓存名称设置不同的过期时间
- 输出INFO级别的监控统计日志
- 二级缓存是否允许缓存NULL值支持配置
- 二级缓存空值允许配置时间倍率
快速开始
集成 Spring 4.x
- 引入layering-cache
- maven 方式
<dependency> <groupId>com.github.xiaolyuh</groupId> <artifactId>layering-cache-aspectj</artifactId> <version>${layering.version}</version> </dependency>
- gradle 方式
compile 'com.github.xiaolyuh:layering-cache:${layering.version}'
声明RedisTemplate
如果项目中没有声明RedisTemplate Bean 可以参考下面链接 声明RedisTemplate
声明CacheManager和LayeringAspect
/** * 多级缓存配置 * * @author yuhao.wang3 */ @Configuration @EnableAspectJAutoProxy public class CacheConfig { @Bean public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) { return new LayeringCacheManager(redisTemplate); } @Bean public LayeringAspect layeringAspect() { return new LayeringAspect(); } }
集成 Spring Boot
引入layering-cache 就可以了
<dependency> <groupId>com.github.xiaolyuh</groupId> <artifactId>layering-cache-starter</artifactId> <version>${layering.version}</version> </dependency>
使用
注解形式
直接在需要缓存的方法上加上Cacheable、CacheEvict、CachePut注解。
- Cacheable注解
@Cacheable(value = "user:info", depict = "用户信息缓存", ttfirstCache = @FirstCache(expireTime = 4, timeUnit = TimeUnit.SECONDS), ttsecondaryCache = @SecondaryCache(expireTime = 10, preloadTime = 3, forceRefresh = true, timeUnit = TimeUnit.SECONDS)) public User getUser(User user) { tlogger.debug("调用方法获取用户名称"); treturn user; }
- CachePut注解
@CachePut(value = "user:info", key = "#userId", depict = "用户信息缓存", ttfirstCache = @FirstCache(expireTime = 4, timeUnit = TimeUnit.SECONDS), ttsecondaryCache = @SecondaryCache(expireTime = 10, preloadTime = 3, forceRefresh = true, timeUnit = TimeUnit.SECONDS)) public User putUser(long userId) { tUser user = new User(); tuser.setUserId(userId); tuser.setAge(31); tuser.setLastName(new String[]{"w", "y", "h"}); treturn user; }
- CacheEvict注解
@CacheEvict(value = "user:info", key = "#userId") public void evictUser(long userId) { } @CacheEvict(value = "user:info", allEntries = true) public void evictAllUser() { }
更多使用方法可以查看官方文档
开源地址:
https://gitee.com/xiaolyuh/layering-cache