java程序内部缓存cache,ExpiringMap


    @Bean(name="cache2")
    public Cache cache2() {
        return new GuavaCache("cache", CacheBuilder.newBuilder().maximumSize(30000).expireAfterWrite(2, TimeUnit.DAYS).build());
    }

    @Autowired
    private Cache cache;
// cache.invalidateAll();  让缓存中的数据都过期


//加载缓存中的内容 没有就查询后加入内部缓存
@Override
    public RcsChatbot getRcsChatbot(String appId) throws Exception {
        RcsChatbot cc = (RcsChatbot) cache.get(appId, () -> {
            RcsChatbot rcsChatbot = null;
            List<RcsChatbot> rcsChatbotList = rcsChatbotMapper.selectRcsChatbotListCache(new RcsChatbot());
            for (RcsChatbot r : rcsChatbotList) {
                if (appId.equals(r.getAppId())) {
                    rcsChatbot = r;
                }
                cache.put(r.getAppId(), r);
            }
            return rcsChatbot;
        });
        return cc;
    }

带过期时间的map缓存

      <!--带过期时间的map-->
      <dependency>
            <groupId>net.jodah</groupId>
            <artifactId>expiringmap</artifactId>
            <version>0.5.9</version>
        </dependency>

    //可变有效期,即单独为每个entity设置过期时间和策略:
    /*private final ExpiringMap<Long, Long> rechargeMoneyMap = ExpiringMap.builder()
            .maxSize(1000)//Map中映射数目超过最大值的大小时,先过期第一个要过期的entity过期
            .expirationPolicy(ExpirationPolicy.ACCESSED)//过期策略的使用:CREATED:  在每次更新元素时,过期倒计时清零,ACCESSED: 在每次访问元素时,过期倒计时清零
            .expiration(config.getAccountTimeOut()==null?5:config.getAccountTimeOut(), TimeUnit.SECONDS)
            .variableExpiration()
            .build();*/

@Bean
public Cache cache() {
    return CacheBuilder.newBuilder().maximumSize(30000).expireAfterWrite(3, TimeUnit.MINUTES).build();

}

@Override
public RcsChatbot getRcsChatbot(String appId) throws Exception {
    RcsChatbot cc = (RcsChatbot) cache.get(appId, () -> {
        RcsChatbot rcsChatbot = null;
        List<RcsChatbot> rcsChatbotList = rcsChatbotMapper.selectRcsChatbotListCache(new RcsChatbot());
        for (RcsChatbot r : rcsChatbotList) {
            if (appId.equals(r.getAppId())) {
                rcsChatbot = r;
            }
            cache.put(r.getAppId(), r);
        }
        return rcsChatbot;
    });
    return cc;
}

版权声明:本文为qq_39477018原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。