当前位置: 首页 > 后端技术 > Java

SpringCache+Caffeine实现本地缓存

时间:2023-04-01 20:47:57 Java

Caffeine简介Caffeine是一款高性能、高命中率、低内存占用、接近最优的本地缓存。简单来说就是GuavaCache的优化增强版。依赖关系org.springframework.bootspring-boot-starter-cachecom.github.ben-manes.caffeinecaffeine开启缓存@EnableCaching注解开启缓存管理功能@SpringBootApplication@EnableCachingpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(应用程序类,参数);}}注入方法1新建一个枚举类publicenumCaches{CACHE_ACCESS_TOKEN(10,7200);/**最大数量*/privateIntegermaxSize;/**以秒为单位的过期时间*/privateIntegerttl;Caches(){}Caches(IntegermaxSize,Integerttl){this.maxSize=maxSize;这个.ttl=ttl;}publicIntegergetMaxSize(){返回maxSize;}酒吧licIntegergetTtl(){返回ttl;}}注册到IOC容器/***本地缓存*@return*/@Bean@PrimarypublicCacheManagercacheManager(){SimpleCacheManagersimpleCacheManager=newSimpleCacheManager();ArrayListcaffeineCaches=newArrayList<>();for(Cachesc:Caches.values()){caffeineCaches.add(newCaffeineCache(c.name(),Caffeine.newBuilder().recordStats().expireAfterWrite(c.getTtl(),TimeUnit.SECONDS).maximumSize(c.getMaxSize()).build()));}simpleCacheManager.setCaches(caffeineCaches);返回简单缓存管理器;}方式二@Bean@PrimarypublicCacheManagercacheManager(){CaffeineCacheManagercaffeineCacheManager=newCaffeineCacheManager();Caffeinecaffeine=Caffeine.newBuilder().expireAfterWrite(60,TimeUnit.MINUTES);caffeineCacheManager.setCaffeine(咖啡因);returncaffeineCacheManager;}使用spring提供的@Cacheable、@CachePut、@CacheEvict等注解,方便使用caffeine缓存@Cacheable(cacheNames="CACHE_ACCESS_TOKEN",key="#root.methodName")publicStringgetAccessToken(Stringcorpid,StringCorpsecret){//todosomething...return"";}问题使用@Cacheable缓存不起作用在失效场景下,将缓存类内部方法调用添加到私有方法中,并添加缓存失效。返回值,然后根据方法名和参数生成缓存key(自定义key除外),而cacheAOP不支持private私有方法的拦截,所以不支持SpringCache注解私有方法。this调用不是代理对象的调用,所以AOP无效,注解无效。求解方法用公共限定符修改;类内部方法调用缓存时,可以使用SpringContextUtil获取当前Bean,调用工具类SpringContextUtil@ComponentpublicclassSpringContextUtilimplementsApplicationContextAware{publicstaticApplicationContextapplicationContext;publicvoidsetApplicationContext(ApplicationContextapplicationContext){SpringContextUtil.applicationContext=applicationContext;}publicstaticObjectgetBean(Stringname){returnapplicationContext.getBean(name);}publicstaticTgetBean(Classclazz){returnapplicationContext.getBean(clazz);staticTgetBean(Stringname,Classclazz){returnapplicationContext.getBean(name,clazz);}publicstaticBooleancontainsBean(Stringname){returnapplicationContext.containsBean(name);}publicstaticBooleanisSingleton(Stringname){returnapplicationContext.isSingleton(name);}公共静态C姑娘getType(字符串名称){返回applicationContext.getType(名称);}}