Spring Boot Cache使用方法整合代码实例

所属分类: 软件编程 / java 阅读数: 55
收藏 0 赞 0 分享

参考:

Spring Cache扩展功能实现

项目地址

使用本地Caffeine缓存

引入依赖包

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

自定义Caffeine配置

CachingConfig.java

package com.vcredit.vmp.checkcenter.config;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.vcredit.vmp.checkcenter.common.properties.CaffeineCacheProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.Duration;
import java.util.*;
/**
 * 缓存配置
 * @author kancy
 */
@Configuration
@EnableCaching
public class CachingConfig {

  @Autowired
  CaffeineCacheProperties caffeineCacheProperties;

  /**
   * 创建基于Caffeine的Cache Manager
   * @return
   */
  @Bean
  @Primary
  @ConditionalOnProperty(prefix = "system.cache.caffeine" , name = "enabled", havingValue = "true")
  public CacheManager caffeineCacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    Map<String, CaffeineCache> cacheMap = new HashMap();

    // 设置全局配置的本地缓存
    List<String> globalCacheNames = caffeineCacheProperties.getCacheName();
    if(globalCacheNames !=null && !globalCacheNames.isEmpty()){
      addCacheObject(cacheMap, globalCacheNames, caffeineCacheProperties.getExpireAfterWrite(),
          caffeineCacheProperties.getExpireAfterAccess(), caffeineCacheProperties.getMaximumSize());
    }

    // 设置自定义属性缓存, 可以覆盖全局缓存
    List<CaffeineCacheProperties.Config> configs = caffeineCacheProperties.getConfigs();
    if(configs != null && !configs.isEmpty()){
      for (CaffeineCacheProperties.Config config : configs) {
        List<String> cacheNames = config.getCacheName();
        if (cacheNames == null || cacheNames.isEmpty()){
          continue;
        }
        Duration expireAfterWrite = Optional.ofNullable(config.getExpireAfterWrite()).orElse(caffeineCacheProperties.getExpireAfterWrite());
        Duration expireAfterAccess = Optional.ofNullable(config.getExpireAfterAccess()).orElse(caffeineCacheProperties.getExpireAfterAccess());
        Long maximumSize = Optional.ofNullable(config.getMaximumSize()).orElse(caffeineCacheProperties.getMaximumSize());
        addCacheObject(cacheMap, cacheNames, expireAfterWrite, expireAfterAccess, maximumSize);
      }
    }
    // 加入到缓存管理器进行管理
    cacheManager.setCaches(cacheMap.values());
    return cacheManager;
  }

  private void addCacheObject(Map<String, CaffeineCache> cacheMap, List<String> cacheNames, Duration expireAfterWrite, Duration expireAfterAccess, Long maximumSize) {
    for (String cacheName : cacheNames) {
      // spring.cache.caffeine: maximumSize=500,expireAfterAccess=10s,expireAfterWrite=15s
      Caffeine<Object, Object> recordStats = Caffeine.newBuilder().recordStats().maximumSize(maximumSize);
      if(expireAfterAccess != null) recordStats.expireAfterAccess(expireAfterAccess);
      if(expireAfterWrite != null) recordStats.expireAfterWrite(expireAfterWrite);
      Cache<Object, Object> cache = recordStats.build();
      CaffeineCache caffeineCache = new CaffeineCache(cacheName,cache);

      // 覆盖添加
      cacheMap.put(cacheName, caffeineCache);
    }
  }
}

CaffeineCacheProperties.java

package com.vcredit.vmp.checkcenter.common.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.List;
/**
 * Caffeine本地缓存自定义配置
 * @author kancy
 */
@Getter
@Setter
@Configuration
@ConfigurationProperties("system.cache.caffeine")
@ConditionalOnProperty(prefix = "system.cache.caffeine" , name = "enabled", havingValue = "true")
public class CaffeineCacheProperties {
  private List<String> cacheName;
  private Duration expireAfterWrite;
  private Duration expireAfterAccess;
  private Long maximumSize = Long.valueOf(-1);
  private List<Config> configs;
  @Getter
  @Setter
  public static class Config {
    private List<String> cacheName;
    Duration expireAfterWrite;
    Duration expireAfterAccess;
    Long maximumSize;
  }
}

application.yml

system.cache.caffeine:
 enabled: true
 # 全局配置
 cacheName: cache1,cache2,cache3
 expireAfterWrite: 60s
 expireAfterAccess: 30s
 maximumSize: 500
 # 自定义配置,cacheName相同可覆盖全局
 configs:
 - cacheName: checkApplyCache
  expireAfterAccess: 10s
 - cacheName: userQueryCache
  expireAfterAccess: 15s

使用缓存

@Cacheable(value = { "checkApplyCache" }, key="#req.md5")
public Result check(CheckReq req) {
  // your code...
  return Result.ok();
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

JavaWeb项目部署到服务器详细步骤详解

这篇文章主要介绍了JavaWeb项目如何部署到服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

IDEA基于支付宝小程序搭建springboot项目的详细步骤

这篇文章主要介绍了IDEA基于支付宝小程序搭建springboot项目的详细步骤,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解SpringBoot应用服务启动与安全终止

这篇文章主要介绍了SpringBoot应用服务启动与安全终止,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Spring Boot启动及退出加载项的方法

这篇文章主要介绍了Spring Boot启动及退出加载项的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Spring Data Jpa 自动生成表结构的方法示例

这篇文章主要介绍了Spring Data Jpa 自动生成表结构的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

IDEA中osgi的开发应用指南详解

这篇文章主要介绍了IDEA中osgi的开发应用指南详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解用maven将dubbo工程打成jar包运行

这篇文章主要介绍了详解用maven将dubbo工程打成jar包运行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

详解Java合并数组的两种实现方式

这篇文章主要介绍了Java合并数组的两种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

使用Jenkins Pipeline自动化构建发布Java项目的方法

这篇文章主要介绍了使用Jenkins Pipeline自动化构建发布Java项目的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

使用Maven配置Spring的方法步骤

这篇文章主要介绍了使用Maven配置Spring的方法步骤,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多