Caffeine简介

Caffeine是一个高性能,高命中率,低内存占用,near optimal 的本地缓存,简单来说它是 Guava Cache 的优化加强版

依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
   <groupId>com.github.ben-manes.caffeine</groupId>
   <artifactId>caffeine</artifactId>
</dependency>

开启缓存

@EnableCaching注解开启使用缓存管理功能

@SpringBootApplication
@EnableCaching
public class Application {

   public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
  }

}

注入

方式一

  1. 新建一个枚举类

public enum Caches {
   CACHE_ACCESS_TOKEN(10, 7200);

   /** 最大数量 */
   private Integer maxSize;

   /** 过期时间 秒 */
   private Integer ttl;

   Caches() {
  }

   Caches(Integer maxSize, Integer ttl) {
       this.maxSize = maxSize;
       this.ttl = ttl;
  }

   public Integer getMaxSize() {
       return maxSize;
  }

   public Integer getTtl() {
       return ttl;
  }

}
  1. 注入到IOC容器

    /**
    * 本地缓存
    * @return
    */
   @Bean
   @Primary
   public CacheManager cacheManager() {
       SimpleCacheManager simpleCacheManager = new SimpleCacheManager();

       ArrayList<CaffeineCache> caffeineCaches = new ArrayList<>();

       for (Caches c : Caches.values()) {
           caffeineCaches.add(new CaffeineCache(c.name(),
                           Caffeine.newBuilder()
                                  .recordStats()
                                  .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
                                  .maximumSize(c.getMaxSize())
                                  .build()
                  )
          );
      }

       simpleCacheManager.setCaches(caffeineCaches);
       return simpleCacheManager;

  }

方式二

@Bean
@Primary
public CacheManager cacheManager() {

   CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
   Caffeine<Object, Object> caffeine = Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES);
   caffeineCacheManager.setCaffeine(caffeine);
   return caffeineCacheManager;

}

使用

可以使用spring提供的@Cacheable、@CachePut、@CacheEvict等注解来方便的使用caffeine缓存

@Cacheable(cacheNames = "CACHE_ACCESS_TOKEN", key = "#root.methodName")
public String getAccessToken(String corpid, String corpsecret) {

  //todo something...
  return "";

}

问题

使用@Cacheable缓存不起作用

失效场景

  • 在私有方法上加缓存

  • 类内部方法调用加缓存

失效原因

Spring cache 的实现原理是基于 AOP 的动态代理实现的:即都在方法调用前后去获取方法的名称、参数、返回值,然后根据方法名称、参数生成缓存的key(自定义的key例外),进行缓存。

AOP 不支持对 private 私有方法的拦截,所以也就不支持私有方法上的 Spring Cache 注解。

this 调用不是代理对象的调用, 所以 AOP 失效,注解失效。

解决办法

  1. 方法用 public 限定符修饰;

  2. 类内部方法调用加缓存时可以用 SpringContextUtil 获取当前 Bean ,由它来调用

工具类

SpringContextUtil

@Component
public class SpringContextUtil implements ApplicationContextAware {

   public static ApplicationContext applicationContext;

   public void setApplicationContext(ApplicationContext applicationContext) {
       SpringContextUtil.applicationContext = applicationContext;
  }

   public static Object getBean(String name) {
       return applicationContext.getBean(name);
  }

   public static <T> T getBean(Class<T> clazz) {
       return applicationContext.getBean(clazz);
  }

   public static <T> T getBean(String name, Class<T> clazz) {
       return applicationContext.getBean(name, clazz);
  }

   public static Boolean containsBean(String name) {
       return applicationContext.containsBean(name);
  }

   public static Boolean isSingleton(String name) {
       return applicationContext.isSingleton(name);
  }

   public static Class<? extends Object> getType(String name) {
       return applicationContext.getType(name);
  }


}
 

Spring Cache + Caffeine实现本地缓存的更多相关文章

  1. spring boot:使用spring cache+caffeine做进程内缓存(本地缓存)(spring boot 2.3.1)

    一,为什么要使用caffeine做本地缓存? 1,spring boot默认集成的进程内缓存在1.x时代是guava cache 在2.x时代更新成了caffeine, 功能上差别不大,但后者在性能上 ...

  2. Spring集成GuavaCache实现本地缓存

    Spring集成GuavaCache实现本地缓存: 一.SimpleCacheManager集成GuavaCache 1 package com.bwdz.sp.comm.util.test; 2 3 ...

  3. 使用Spring Cache + Redis + Jackson Serializer缓存数据库查询结果中序列化问题的解决

    应用场景 我们希望通过缓存来减少对关系型数据库的查询次数,减轻数据库压力.在执行DAO类的select***(), query***()方法时,先从Redis中查询有没有缓存数据,如果有则直接从Red ...

  4. Caffeine Cache-高性能Java本地缓存组件

    前面刚说到Guava Cache,他的优点是封装了get,put操作:提供线程安全的缓存操作:提供过期策略:提供回收策略:缓存监控.当缓存的数据超过最大值时,使用LRU算法替换.这一篇我们将要谈到一个 ...

  5. springboot之本地缓存(guava与caffeine)

    1. 场景描述 因项目要使用本地缓存,具体为啥不用redis等,就不讨论,记录下过程,希望能帮到需要的朋友. 2.解决方案 2.1 使用google的guava作为本地缓存 初步的想法是使用googl ...

  6. JAVA缓存规范 —— 虽迟但到的JCache API与天生不俗的Spring Cache

    大家好,又见面了. 本文是笔者作为掘金技术社区签约作者的身份输出的缓存专栏系列内容,将会通过系列专题,讲清楚缓存的方方面面.如果感兴趣,欢迎关注以获取后续更新. 有诗云"纸上得来终觉浅,绝知 ...

  7. Spring Cache缓存技术的介绍

    缓存用于提升系统的性能,特别适用于一些对资源需求比较高的操作.本文介绍如何基于spring boot cache技术,使用caffeine作为具体的缓存实现,对操作的结果进行缓存. demo场景 本d ...

  8. Spring Cache缓存框架

    一.序言 Spring Cache是Spring体系下标准化缓存框架.Spring Cache有如下优势: 缓存品种多 支持缓存品种多,常见缓存Redis.EhCache.Caffeine均支持.它们 ...

  9. Spring Cache扩展:注解失效时间+主动刷新缓存

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  10. 使用guava cache在本地缓存热点数据

    某些热点数据在短时间内可能会被成千上万次访问,所以除了放在redis之外,还可以放在本地内存,也就是JVM的内存中. 我们可以使用google的guava cache组件实现本地缓存,之所以选择gua ...

随机推荐

  1. 生信入门必须掌握的 30 个 Linux 命令

    学习生物信息,Linux 是必须掌握的内容,其实常用的 Linux 命令也就 30 个左右,而且这些命令都是单词的简写,记忆起来并不困难.这里列出了常用的 30 个命令. 1. cd Change d ...

  2. 分布式数据库 Join 查询设计与实现浅析

    相对于单例数据库的查询操作,分布式数据查询会有很多技术难题. 本文记录 Mysql 分库分表 和 Elasticsearch Join 查询的实现思路,了解分布式场景数据处理的设计方案. 文章从常用的 ...

  3. Kubernetes(k8s)访问控制:身份认证

    目录 一.系统环境 二.前言 三.Kubernetes访问控制 四.身份认证简介 五.身份认证 5.1 配置客户端机器 5.2 使用base auth的方式进行认证 5.3 使用token的方式进行认 ...

  4. 【TVM模型编译】0.onnx模型优化流程.md

    本文以及后续文章,着重于介绍tvm的完整编译流程. 后续文章将会按照以上流程,介绍tvm源码.其中涉及一些编程技巧.以及tvm概念,不在此部分进行进一步讲解,另有文章进行介绍. 首先介绍一下,从onn ...

  5. 【翻译】高效numpy指北

    ref:link why numpy 运算高效 numpy 内存结构 一块内存区域 dtype 确定了内存区域数据类型 metadata 比如 shape.strides etc 注:numpy 内存 ...

  6. 自然语言处理(NaturalLanguageProcessing,NLP)领域的100篇热门博客文章标题如下:

    目录 文章标题:<自然语言处理(Natural Language Processing,NLP)领域的100篇热门博客文章标题如下> 背景介绍: 随着人工智能技术的不断发展和普及,自然语言 ...

  7. GPT3与机器翻译的结合:探索新的语言翻译技术

    目录 引言 随着全球化的加速和人工智能的快速发展,机器翻译成为了许多企业.机构和个人的痛点.虽然已有多种机器翻译技术,但基于自然语言处理和深度学习的机器翻译一直缺乏有效的解决方案,这导致机器翻译的准确 ...

  8. ShardingSphere5入门到实战

    ShardingSphere5入门到实战 第01章 高性能架构模式 互联网业务兴起之后,海量用户加上海量数据的特点,单个数据库服务器已经难以满足业务需要,必须考虑数据库集群的方式来提升性能.高性能数据 ...

  9. Python 逻辑表达式的妙用

    今天偶然看到有这样一段代码,感到很惊讶: super().__init__(package_name or (robot_name + "_moveit_config")) 语义非 ...

  10. 春节无法线下社交聚会,来线上“一起X”共享体验

    引语: 共享体验或许是全真互联网时代最显著的标志. 被疫情深刻改变的一年里,人们的社交关系和社交活动正在发生巨大的改变. 一方面,从线下转线上,我们能通过互联网连接更多的人,参与各种形式的社交活动,将 ...