layering-cache

layering-cache

layering-cache是一个支持分布式环境的多级缓存框架,使用方式和spring-cache类似,主要目的是在使用注解的时候支持配置过期时间。

layering-cache其实是一个两级缓存,一级缓存使用Caffeine作为本地缓存,二级缓存使用redis作为集中式缓存。并且基于redis的Pub/Sub做缓存的删除,所以它是一个适用于分布式环境下的一个缓存系统。

支持

  • 支持缓存监控统计
  • 支持缓存过期时间在注解上直接配置
  • 支持二级缓存的自动刷新(当缓存命中并发现缓存将要过期时会开启一个异步线程刷新缓存)
  • 刷新缓存分为强刷新和软刷新,强刷新直接调用缓存方法,软刷新直接改缓存的时间
  • 缓存Key支持SpEL表达式
  • 新增FastJsonRedisSerializer,KryoRedisSerializer序列化,重写String序列化。
  • 支持同一个缓存名称设置不同的过期时间
  • 输出INFO级别的监控统计日志
  • 二级缓存是否允许缓存NULL值支持配置
  • 二级缓存空值允许配置时间倍率

快速开始

集成 Spring 4.x

  1. 引入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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值