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

参考:

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();
}

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

(0)

相关推荐

  • springboot接入cachecloud redis示例实践

    最近项目中需要接入  Redis CacheCloud,   CacheCloud是一个开源的 Redis 运维监控云平台,功能十分强大,支持Redis 实例自动部署.扩容.碎片管理.统计.监控等功能, 特别是支持单机.sentinel .cluster三种模式的自动部署,搭建redis集群一步到位轻松搞定. java项目中 接入 CacheCloud redis的方式主要有两种. 第一种就是在 CacheCloud 上创建好redis实例后将对应的IP,端口直接配置以配置形式应用到项目中,优点

  • Spring Boot集成Ehcache缓存解决方式

    本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能.在Spring Boot应用程序中,我们可以通过Spring Caching来快速搞定数据缓存. 接下来我们将介绍如何在三步之内搞定 Spring Boot 缓存. 1. 创建一个Spring Boot工程 你所创建的Spring Boot应用程序的maven依赖文件至少应该是下面的样子: <?xml version="1.0" encoding="UTF-8"?

  • Spring Boot整合Spring Cache及Redis过程解析

    这篇文章主要介绍了Spring Boot整合Spring Cache及Redis过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.安装redis a.由于官方是没有Windows版的,所以我们需要下载微软开发的redis,网址: https://github.com/MicrosoftArchive/redis/releases b.解压后,在redis根目录打开cmd界面,输入:redis-server.exe redis.wind

  • 使用ehcache三步搞定springboot缓存的方法示例

    本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能.在Spring Boot应用程序中,我们可以通过Spring Caching来快速搞定数据缓存.接下来我们将介绍如何在三步之内搞定Spring Boot缓存. 1. 创建一个Spring Boot工程并添加Maven依赖 你所创建的Spring Boot应用程序的maven依赖文件至少应该是下面的样子: <?xml version="1.0" encoding="UTF-8

  • SpringBoot加入Guava Cache实现本地缓存代码实例

    这篇文章主要介绍了SpringBoot加入Guava Cache实现本地缓存代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在pom.xml中加入guava依赖 <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version>

  • springboot使用GuavaCache做简单缓存处理的方法

    问题背景 实际项目碰到一个上游服务商接口有10秒的查询限制(同个账号). 项目中有一个需求是要实时统计一些数据,一个应用下可能有多个相同的账号.由于服务商接口的限制,当批量查询时,可能出现同一个账号第一次查询有数据,但第二次查询无数据的情况. 解决方案 基于以上问题,提出用缓存的过期时间来解决. 这时,可用Redis和Guava Cache来解决: 当批量查询时,同一个账号第一次查询有数据则缓存并设置过期时间10s, 后续查询时直接从缓存中取,没有再从服务商查询. 最终采用Guava Cache

  • SpringBoot中Shiro缓存使用Redis、Ehcache的方法

    SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这shiro基础之上的补充内容 第一种:Redis缓存,将数据存储到redis 并且开启session存入redis中. 引入pom <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifac

  • Spring Boot如何使用EhCache演示

    一.EhCache使用演示 EhCache是一个纯Java的进程内缓存框架,具有快速.精干等特点,Hibernate中的默认Cache就是使用的EhCache. 本章节示例是在Spring Boot集成Spring Cache的源码基础上进行改造.源码地址:https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cache 使用EhCache作为缓存,我们先引入相关依赖. <dependency> &l

  • Spring boot redis cache的key的使用方法

    在数据库查询中我们往往会使用增加缓存来提高程序的性能,@Cacheable 可以方便的对数据库查询方法加缓存.本文主要来探究一下缓存使用的key. 搭建项目 数据库 mysql> select * from t_student; +----+--------+-------------+ | id | name | grade_class | +----+--------+-------------+ | 1 | Simone | 3-2 | +----+--------+-----------

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

    参考: Spring Cache扩展功能实现 项目地址 使用本地Caffeine缓存 引入依赖包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>com.github.ben

  • spring boot aop 记录方法执行时间代码示例

    本文研究的主要是spring boot aop 记录方法执行时间的实现代码,具体如下. 为了性能调优,需要先统计出来每个方法的执行时间,直接在方法前后log输出太麻烦,可以用AOP来加入时间统计 添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency&

  • spring boot多数据源动态切换代码实例

    这篇文章主要介绍了spring boot多数据源动态切换代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 当项目中存在多数据源时,就涉及到数据源的动态切换,通过研究,特此记录一下. 1.maven依赖 <!--数据库连接--> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> &

  • Kotlin + Spring Boot 请求参数验证的代码实例

    编写 Web 应用程序的时候,经常要做的事就是要对前端传回的数据进行简单的验证,比如是否非空.字符长度是否满足要求,邮箱格式是否正确等等.在 Spring Boot 中,可以使用 Bean Validation (JSR-303) 技术通过注解的方式来进行参数验证. 准备 DTO 对象 data class UserRegisterModel( @get: NotEmpty(message = "User name is required") @get: Size(message =

  • spring boot 监听容器启动代码实例

    在使用Spring框架开发时, 有时我们需要在spring容器初始化完成后做一些操作, 那么我们可以通过自定义ApplicationListener 来实现. 自定义监听器 @Component public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEve

  • Spring boot文件路径映射配置代码实例

    springboot配置本地资源映射路径需要配置一下映射资源位置,下面来介绍一下过程. 1.添加配置类 package org.jcut.tools; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.ResourceH

  • spring boot项目导入依赖后代码报错问题的解决方法

    代码截图如图所示(由于本人问题已经解决,没来得及截图,所以在网上找了一张图片) ​ 针对图中所示的情况,可参考一下解决方案: 方案一: 在 Idea 导入 Spring Boot 项目代码报红,试过更改maven配置,maven clean操作,执行-U idea:idea等命令还是提示:cannot resolve symbol 'SpringBootApplication' .我最终解决方法是导入要导入项目的pom.xml文件,而不是导入现有项目解决.选择pom.xml后会弹出提示框,选择a

  • Spring Boot集成Kafka的示例代码

    本文介绍了Spring Boot集成Kafka的示例代码,分享给大家,也给自己留个笔记 系统环境 使用远程服务器上搭建的kafka服务 Ubuntu 16.04 LTS kafka_2.12-0.11.0.0.tgz zookeeper-3.5.2-alpha.tar.gz 集成过程 1.创建spring boot工程,添加相关依赖: <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&qu

  • Spring Boot 与 Vue.js 整合流程

    一直都想尝试做前后端分离,我之前一直是学 Java 的,所以后端选择了 Spring Boot:前端选择了 Vue.js 这个轻量.易上手的框架.网上其实已经有了不少 Spring Boot 和 Vue.js 整合的资料,Github 上就有好多 repo,但是每当我指望按图索骥的时候就会出现各种各样奇怪的 bug,上 Stack Overflow 问了也没人搭理.前前后后研究了差不多三个星期,现在总算是理清楚了. 本文重点介绍我在实践过程中的基本流程,以及我遇到的一个困扰了我好久的问题,就是如

  • spring boot 若依系统整合Ueditor部署时上传图片错误问题

    前言:国庆假期找了个ruoyi版本的cms玩玩,从git上看,介绍如下图: 后台部分截图: 编辑​ 编辑​ 编辑​ 编辑​ 前台blog截图: 编辑​ 编辑​ 看上去还可以不错,于是clone下来玩玩,结果发现,发布文章的时候,编辑器有问题,上传不了图片,还有其他几个地方有问题,怎么解决呢?自己上手撸代码,修改呗.于是,下载了ueditor的源码,加到项目中,进行修改.现在已经修改完成,并且也发布到的服务器上了,欢迎大家访问测试.文末会有凯哥修改后的git地址o~ 正文: 在spring boo

随机推荐