当使用redis作为spring cache组件时,使用注解@CacheExpire支持自定义过期时间
- 支持方法级别设置过期时间
- 支持在类上添加注解,该类下的缓存方法通用过期时间
- 支持忽略功能
在spring-boot-starter-data-redis基础上改变了RedisCacheManager其getCache原始行为
在其基础上添加设置自定义过期时间的功能
因为redis-cache-expire-spring-boot-starter并没有集成spring-boot-starter-data-redis所以需要
手动引入依赖
主要是为了方便使用各自的
spring-boot-starter-data-redis版本
- 引入
spring-boot-starter-data-redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>- 引入本starter依赖
<dependency>
<groupId>top.luhancc.redis</groupId>
<artifactId>redis-cache-expire-spring-boot-starter</artifactId>
</dependency>还没有放到maven中央仓库
- 和使用
spring cache一样 使用@EnableCaching开启缓存即可
@SpringBootApplication
@EnableCaching
public class RedisCacheExpireApplication {
public static void main(String[] args) {
SpringApplication.run(RedisCacheExpireApplication.class, args);
}
}- 在需要添加缓存过期时间的方法上添加
@CacheExpire注解
方法级别
@Service
public class CacheService {
@Cacheable(value = "cache-test", key = "targetClass + methodName")
@CacheExpire(value = 100)
public String data() {
System.out.println("没走缓存,直接查询");
return "hello this data is redis cache";
}
@Cacheable(value = "cache-test", key = "targetClass + methodName")
public String data2() {
System.out.println("没走缓存,直接查询");
return "hello this data is redis cache is not expire";
}
}类级别
@CacheExpire
@Cacheable(value = "cache-test2", key = "targetClass + methodName")
@Service
public class CacheService2 {
public String data4() {
return "this is cache data 2";
}
@CacheExpire(value = 10, ignore = true)
public String data3() {
return "this is cache data 3";
}
}- Fork 本仓库
- 新建 feature/xxx 分支
- 提交代码
- 新建 Pull Request