SpringBoot整合EhCache3.6加过期机制

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。

如果你认为文章帮助了你,请君点个赞哦。

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术武器库

一句真诚的谢谢,胜过千言万语

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值