为监控而生的多级缓存框架 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 = "用户信息缓存",
		firstCache = @FirstCache(expireTime = 4, timeUnit = TimeUnit.SECONDS),
		secondaryCache = @SecondaryCache(expireTime = 10, preloadTime = 3, forceRefresh = true, timeUnit = TimeUnit.SECONDS))
public User getUser(User user) {
	logger.debug("调用方法获取用户名称");
	return user;
}
  • CachePut注解
@CachePut(value = "user:info", key = "#userId", depict = "用户信息缓存",
		firstCache = @FirstCache(expireTime = 4, timeUnit = TimeUnit.SECONDS),
		secondaryCache = @SecondaryCache(expireTime = 10, preloadTime = 3, forceRefresh = true, timeUnit = TimeUnit.SECONDS))
public User putUser(long userId) {
	User user = new User();
	user.setUserId(userId);
	user.setAge(31);
	user.setLastName(new String[]{"w", "y", "h"});
	return 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

更多更优质的资讯,请关注我,你的支持会鼓励我不断分享更多更好的优质文章。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注