Ehcache3.6官方文档:http://www.ehcache.org/documentation/3.6/getting-started.html
本来不想加缓存的,但奈何我的接口还要调用另外一个公司的接口,那个公司的接口老是超时,导致页面加载很慢,本来想用redis的key过期机制的,但还要对redis的配置进行修改,而redis用的又是阿里云RDS,但奈何密码又不在我在,还要去问。。。算了用java本地缓存吧!开始~~
1、依赖
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.6.3</version>
</dependency>
2、配置
@Configuration
public class EhCacheConfig {
@Bean
public CacheManager cacheManager() {
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("preConfigured",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, ResponseObject.class,
ResourcePoolsBuilder.heap(1000L))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(20))))
.build();
cacheManager.init();
return cacheManager;
}
}
2.1、 名词解释
preConfigured:缓存的名称,可以创建多个,可以对每个缓存进行不同的设置。比方说对A缓存设置过期时间,B缓存不设置过期时间。
String.class,ResponseObject.class:你可以理解为是key是String类型的,value是ResponseObject类型的。等会获取缓存是根据String类型key来获取ResponseObject类型的value的。
heap(1000L):代表preConfigured下的缓存最多存1000个key,如果是1001则把第一个缓存删除。当然也可以设置offHeap()这个代表如果超过heap()设置的缓存数,则把缓存存到offHeap()设置的磁盘上。(本次没用)
withExpiry:对preConfigured下的缓存设置超时时间(上面的例子是20秒自动过期),EhCache的缓存过期机制有3种,想了解的可以去官网。
3、使用
@Resource
private CacheManager cacheManager;
@RequestMapping("/put")
public void putCache() {
Cache<String, ResponseObject> cache = cacheManager.getCache("preConfigured", String.class, ResponseObject.class);
ResponseObject responseObject = new ResponseObject();
responseObject.setData(Lists.newArrayList());
responseObject.setStatus(ResultCode.BUSINESS_SUCESS.getErrorCode());
responseObject.setMsg(ResultCode.BUSINESS_SUCESS.getError());
cache.put("138xxxxxx",responseObject);
}
@RequestMapping("/get")
public ResponseObject getCache() {
Cache<String, ResponseObject> cache = cacheManager.getCache("preConfigured", String.class, ResponseObject.class);
ResponseObject responseObject = cache.get("138xxxxxx");
return responseObject;
注意:
使用上面那种配置,不要加@EnableCaching。
如果你认为文章帮助了你,请君点个赞哦。