1 依赖
<dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId><version>2.9.2</version>
</dependency>
2 应用
2.1 创建缓存实例
下面是创建支持缓存自动过期的缓存实例。
/*** 创建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();}}
2.2 使用
@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<>();
}
3 参考文献
(1)java缓存框架Caffeine详解