<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.2</version>
</dependency>
下面是创建支持缓存自动过期的缓存实例。
/**
* 创建Caffeine缓存实例
*/
@Configuration
public class CaffeineConfig {
/**
* 通用Caffeine缓存的过期时间。单位:s.
*/
@Value("${expireTime.caffeineCacheOfCommon:5}")
private Integer expireTime4CaffeineCacheOfCommon;
@Bean("caffeineCacheOfCommon")
public Cache<String, Object> caffeineCacheOfCommon() {
return Caffeine.newBuilder()
// 设置创建缓存或者最后一次更新缓存后,经过固定时间后数据过期
.expireAfterWrite(expireTime4CaffeineCacheOfCommon, TimeUnit.SECONDS)
.build();
}
}
@Resource
private TestDubboService testDubboService;
@Resource
private Cache<String, Object> caffeineCacheOfCommon;
public List<TestDto> queryDto(String province) {
if (StringUtils.isBlank(province)) {
return new ArrayList<>();
}
try {
List<TestDto> testList = (List<TestDto>) caffeineCacheOfCommon.getIfPresent(province);
if (testList != null) {
return testList;
}
testList = testDubboService.queryDtoByProvince(province);
if (testList == null) {
return new ArrayList<>();
}
caffeineCacheOfCommon.put(province, testList);
return testList;
} catch (Exception e) {
log.error("queryDto error.", e);
}
return new ArrayList<>();
}