小工具知识网

当前位置: 首页 > 行业知识 > SpringBoot集成系列--Caffeine

行业知识

SpringBoot集成系列--Caffeine

2026-11-11 17:33:26 来源:互联网转载

文章目录

  • 一、介绍
  • 二、代码
    • 1、添加依赖
    • 2、通过spring缓存实现
      • 1)配置
      • 2)使用
      • 3、Caffeine
        • 1)定义配置类
        • 2)使用
        • 3)抽取公共代码
        • 三、通过Caffeine+Redis实现二级缓存
        • 四、小结

          一、介绍

          Caffeine是一个基于Java的高性能缓存库,旨在提供快速、可扩展和灵活的缓存解决方案。它提供了一种简单而强大的方式来管理和访问缓存数据,以提高应用程序的性能和响应速度。

          Caffeine的设计目标是在内存中存储和管理数据,以减少对慢速数据源(如数据库或网络)的访问次数。它通过使用内存作为缓存介质,可以快速地读取和写入数据,从而提供更高的吞吐量和更低的延迟。

          Caffeine提供了丰富的缓存功能,包括自动加载、过期策略、缓存回收和统计信息等。自动加载功能可以在缓存中不存在某个键对应的值时,自动从数据源加载并存储该值。过期策略可以设置缓存项的过期时间,以确保缓存中的数据始终保持最新。缓存回收功能可以根据一定的策略来回收不再使用的缓存项,以释放内存空间。统计信息功能可以帮助开发人员监控和优化缓存的使用情况。

          二、代码

          1、添加依赖

          在pom.xml文件中添加caffeine的依赖

              com.github.ben-manes.caffeine    caffeine

          2、通过spring缓存实现

          1)配置

          我们配置缓存大小为1,过期为30s,方便我们调试

          • 方式1:在application.properties文件中配置caffeine
            spring.cache.type=caffeinespring.cache.caffeine.spec=maximumSize=1,expireAfterWrite=30s
            • 方式2:新增CacheConfig缓存配置类,重写CacheManager 注入Spring
              @Configurationpublic class CacheConfig {@Beanpublic CacheManager cacheManager() {CaffeineCacheManager cacheManager = new CaffeineCacheManager();cacheManager.setCaffeine(caffeineCacheBuilder());return cacheManager;}private Caffeine caffeineCacheBuilder() {return Caffeine.newBuilder().maximumSize(1).expireAfterWrite(Duration.ofSeconds(30));}}

              2)使用

              • 方式1:@Cacheable
                @PostMapping("/get")@Cacheable(value = "forlan")public Object get(@Param("key") String key) {Object data = null;return "当前时间为" + LocalDateTime.now() + ",获取的内容为:" + data;}

                注:@Cacheable(value = “forlan”)表示我们的缓存的名称为forlan,大小为前面设置maximumSize,通过配置不同的缓存名称,可以实现每个缓存大小独立管理

                存在问题:上面这种方式,无法手动set缓存,只有在获取的时候,才会塞缓存进去

                • 方式2:CacheManager类
                  @PostMapping("/setCaffeine")public String setCaffeine1(@Param("key") String key, @Param("value") String value) {Cache caffeineCacheBuilder = cacheManager.getCache("forlan");caffeineCacheBuilder.put(key, value);return "ok";}@PostMapping("/getCaffeine")public Object getCaffeine1(@Param("key") String key) {Cache caffeineCacheBuilder = cacheManager.getCache("forlan");return "当前时间为" + LocalDateTime.now() + ",获取的内容为:" + caffeineCacheBuilder.get(key).get();}

                  3、Caffeine

                  1)定义配置类

                  新增CaffeineConfig配置类,注入名为forlanCaffeineCacheCaffeine到spring中,如下:

                  @Configurationpublic class CaffeineConfig {@Beanpublic Cache forlanCaffeineCache() {return Caffeine.newBuilder().maximumSize(1).expireAfterWrite(Duration.ofSeconds(30)).build();}}

                  定义spring上下文工具类,方便我们获取bean

                  @Componentpublic class SpringUtils implements ApplicationContextAware {private static ApplicationContext applicationContext = null;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {if (SpringUtils.applicationContext == null) {SpringUtils.applicationContext = applicationContext;}}public static ApplicationContext getApplicationContext() {return applicationContext;}public static Object getBean(String name) {return getApplicationContext().getBean(name);}public static  T getBean(Class clazz) {return getApplicationContext().getBean(clazz);}public static  T getBean(String name, Class clazz) {return getApplicationContext().getBean(name, clazz);}public static String getEnv(String envName) {Environment env = SpringUtils.getApplicationContext().getEnvironment();String envValue = env.getProperty(envName);return envValue;}public static String getProfile() {Environment env = SpringUtils.getApplicationContext().getEnvironment();String[] profile = env.getActiveProfiles();if(profile != null && profile.length > 0) {return profile[0];}return "";}}

                  2)使用

                  @PostMapping("/setCaffeine")public String setCaffeine(@Param("key") String key, @Param("value") String value) {Cache caffeine = (Cache) SpringUtils.getBean("forlanCaffeineCache");caffeine.put(key, value);return "ok";}@PostMapping("/getCaffeine")public Object getCaffeine(@Param("key") String key) {Cache caffeine = (Cache) SpringUtils.getBean("forlanCaffeineCache");Object value = caffeine.asMap().get(key);return value;}

                  3)抽取公共代码

                  可以抽成一个工具类,方便我们调用,如下:

                  public class CaffeineUtils {private static Cache caffeineCache;static {caffeineCache = (Cache) SpringUtils.getBean("forlanCaffeineCache");}public static void put(String key, Object value) {caffeineCache.put(key, value);}public static Object get(String key) {return caffeineCache.asMap().get(key);}}

                  使用

                  @PostMapping("/setCaffeine")public String setCaffeine(@Param("key") String key, @Param("value") String value) {CaffeineUtils.put(key, value);return "ok";}@PostMapping("/getCaffeine")public Object getCaffeine(@Param("key") String key) {Object value = CaffeineUtils.get(key);return value;}

                  三、通过Caffeine+Redis实现二级缓存

                  使用spring的注解@Cacheable配合redisTemplate,实现二级缓存,代码如下:

                  @PostMapping("/get")@Cacheable(value = "forlan")public Object get(@Param("key") String key) {Object data = redisTemplate.opsForValue().get(key);return "当前时间为" + LocalDateTime.now() + ",获取的内容为:" + data;}

                  四、小结

                  总的来说,在SpringBoot中使用Caffeine,大体有如下几种方式:

                  • @Cacheable
                  • CacheManager类
                  • Caffeine类

上一篇:怎么调用华为云服务器功能?

下一篇:怎么搭建服务器国外网络?