当使用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