当前位置: 首页 > article >正文

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


http://www.kler.cn/a/397723.html

相关文章:

  • 谷歌AI进军教育,这将改变未来?
  • MySQL【七】
  • 计算机网络 (3)计算机网络的性能
  • 前后端、网关、协议方面补充
  • Spark RDD sortBy算子什么情况会触发shuffle
  • 浅谈React的虚拟DOM
  • 将 HTML 转换为 JSX:JSX 和 JSX 规则
  • 【项目开发】分析六种常用软件架构
  • ISCTF2024
  • 算法沉淀一:双指针
  • 【Android Compose原创组件】可拖动滚动条的完美实现
  • 算法:快排(三指针算法)
  • YashanDB 23.2.3安装过程,并使用DBeaver进行连接
  • 【如何获取股票数据47】Python、Java等多种主流语言实例演示获取股票行情api接口之沪深指数历史分时KDJ数据获取实例演示及接口API说明文档
  • windows C#-创建记录类型(下)
  • Vue3 -- 项目配置之eslint【企业级项目配置保姆级教程1】
  • mysql数据迁移PolarDB
  • ubuntu安装 Pycharm
  • Prometheus面试内容整理-数据持久化和高可用
  • cocosCreator视频web模式播放踩坑解决
  • 分页查询我的课表
  • 性能高于Transformer模型1.7-2倍,彩云科技发布基于DCFormer架构通用大模型云锦天章
  • 什么是Spring Boot Actuator
  • 第二十二章 TCP 客户端 服务器通信 - TCP设备的OPEN和USE命令关键字
  • 【网络云计算】2024第46周周考-磁盘管理的基础知识-RAID篇
  • rust逆向初探