自学内容网 自学内容网

spring-cache concurrentHashMap 自定义过期时间

1.自定义实现缓存构建工厂

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;


public class ExpiringConcurrentMapCacheFactoryBean
implements FactoryBean<ConcurrentMapCache>, BeanNameAware, InitializingBean {

private String name = "";

@Nullable
private ConcurrentMap<Object, Object> store;

private boolean allowNullValues = true;

@Nullable
private ConcurrentMapCache cache;

@Setter
@Getter
private long expiringMillis = 1000*60*60*24;//默认一天

public void setName(String name) {
this.name = name;
}


public void setStore(ConcurrentMap<Object, Object> store) {
this.store = store;
}


public void setAllowNullValues(boolean allowNullValues) {
this.allowNullValues = allowNullValues;
}

@Override
public void setBeanName(String beanName) {
if (!StringUtils.hasLength(this.name)) {
setName(beanName);
}
}

@Override
public void afterPropertiesSet() {
if (store==null){
store = new ConcurrentHashMap<>(256);
}
ExpiringConcurrentMapCache expiringConcurrentMapCache = new ExpiringConcurrentMapCache(this.name, store, this.allowNullValues);
expiringConcurrentMapCache.setExpiringMillis(expiringMillis);
this.cache = expiringConcurrentMapCache;
}


@Override
@Nullable
public ConcurrentMapCache getObject() {
return this.cache;
}

@Override
public Class<?> getObjectType() {
return ExpiringConcurrentMapCache.class;
}

@Override
public boolean isSingleton() {
return true;
}

}

2.自定义实现缓存

import lombok.Getter;
import lombok.Setter;
import org.springframework.cache.concurrent.ConcurrentMapCache;

import java.util.concurrent.ConcurrentMap;

public class ExpiringConcurrentMapCache extends ConcurrentMapCache {

    @Setter
    @Getter
    private long expiringMillis = 1000*60*60*24;//默认一天

    public ExpiringConcurrentMapCache(String name, ConcurrentMap<Object, Object> store, boolean allowNullValues) {
        super(name, store, allowNullValues);
    }


    // 自定义缓存值,包含数据和过期时间
    public static class CacheValue {
        @Getter
        private final Object value;
        private final long expirationTime;

        public CacheValue(Object value, long expirationTime) {
            this.value = value;
            this.expirationTime = System.currentTimeMillis() + expirationTime;
        }

        public boolean isExpired() {
            long l = System.currentTimeMillis();
            return  l > expirationTime;
        }
    }

    @Override
    public void put(Object key, Object value) {
        // 设置过期时间,例如 5 分钟
        CacheValue cacheValue = new CacheValue(value, expiringMillis);
        super.put(key, cacheValue);
    }

    @Override
    protected Object lookup(Object key) {
        CacheValue cacheValue = (CacheValue) super.lookup(key);
        if (cacheValue != null && !cacheValue.isExpired()) {
            return cacheValue.getValue();
        }
        return null;
    }


}

3.自定义缓存配置

import com.cardcharge.share.cache.ExpiringConcurrentMapCacheFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;

@Configuration
public class SpringCacheConfiguration {

    @Value("${spring.cache.expireTimeMillis}")
    private Long springCacheExpireTime;
    @Bean
    ExpiringConcurrentMapCacheFactoryBean defaultCache() {
        ExpiringConcurrentMapCacheFactoryBean cache = new ExpiringConcurrentMapCacheFactoryBean();
        if (springCacheExpireTime!=null){
            cache.setExpiringMillis(springCacheExpireTime);
        }
        cache.setName("nbCard");
        return cache;
    }

    @Bean
    CacheManager cacheManager(ConcurrentMapCache defaultCache) {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Collections.singletonList(defaultCache));
        return cacheManager;
    }




}

4.在需要缓存的 方法上加 注解

  /**
     * 查所有
     * @param tokenInfo
     * @return
     * @throws CodeException
     */
    @Override
    @Cacheable(cacheManager = "cacheManager",cacheNames = "nbCard",key = "#root.target.All_Nb_Card_Vo_Cache_Key",sync = true)
    public List<NbCardVo> findByRoleAll(TokenInfoDto tokenInfo) throws CodeException {
        ExecutorService executorService = Executors.newFixedThreadPool(16);//开启固定线程
        List<NbCardVo> result = new CopyOnWriteArrayList<>();

5.修改的缓存上面加注解

 @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheManager = "cacheManager",cacheNames = "nbCard",key = "#root.target.All_Nb_Card_Vo_Cache_Key")
    public void purchaseUpdate(PurchaseUpdateNbCardBasicInfo nbCardDto, TokenInfoDto tokenInfo) throws CodeException


原文地址:https://blog.csdn.net/qq_53374893/article/details/143819126

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!