spring-cache concurrentHashMap 自定义过期时间

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

java 复制代码
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.自定义实现缓存

java 复制代码
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.自定义缓存配置

java 复制代码
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.在需要缓存的 方法上加 注解

java 复制代码
  /**
     * 查所有
     * @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.修改的缓存上面加注解

java 复制代码
 @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
相关推荐
新知图书37 分钟前
Rust编程与项目实战-函数指针
开发语言·后端·rust
开心工作室_kaic1 小时前
ssm126基于HTML5的出租车管理系统+jsp(论文+源码)_kaic
java·前端·html5
卷心菜是俺2 小时前
Sping全面复习
java·开发语言·数据库·junit·java-ee·log4j·maven
是老余2 小时前
算法之二分查找优化:leetcode34:在排序数组中查找元素的第一个和最后一个位置
java·开发语言·算法
fa_lsyk2 小时前
Spring:bean的配置
java·后端·spring
bug修复机器人2 小时前
springBoot项目中,参数更改为配置文件
java·spring boot·spring
冰芒猓2 小时前
Spring中的Bean
java·spring·rpc
苹果电脑的鑫鑫2 小时前
uni-app使用watch监听数据,当数据变化时页面没有根据变化数据渲染解决方法
java·前端·uni-app
计算机学姐3 小时前
基于Python爬虫大屏可视化的个性化小说书籍推荐系统
开发语言·vue.js·后端·爬虫·python·mysql·django