当前位置: 首页 > news >正文

【7】Spring Boot 3 集成组件:缓存组件 spring cache + spring data redis

目录

  • 【7】Spring Boot 3 集成组件:缓存组件 spring cache + spring data redis
    • 什么是缓存抽象
      • 声明式注解
      • JSR-107对应
      • SpEL上下文数据
    • 引入依赖
    • cache 支持的缓存类型
    • 缓存类型配置
      • NONE
      • SIMPLE
      • REDIS
        • 自定义配置
      • CAFFEINE
    • Hazelcast
    • ...
    • 总结

个人主页: 【⭐️个人主页】
需要您的【💖 点赞+关注】支持 💯


【7】Spring Boot 3 集成组件:缓存组件 spring cache + spring data redis

📖 本文核心知识点:

  • spring cache 抽象和注解
  • cache 支持的缓存类型
  • spring cache + spring data redis 配置
  • redis序列化

本章使用的spring版本
spring boot version: 3.1.5

什么是缓存抽象

  • 官网-缓存抽象
    使用翻译软件阅读
  • 主要阅读的知识点
  1. 缓存抽象的作用
  2. spring缓存的声明式注解
  3. spring缓存的生成key策略和如何自定义keyGenerator
  4. 缓存支持的后端类型

声明式注解

Spring 缓存注解说明
@Cacheable触发缓存填充。
@CacheEvict触发缓存退出。
@CachePut在不干扰方法执行的情况下更新缓存。
@Caching将多个缓存操作重新组合到一个方法上。
@CacheConfig在类级别共享一些常见的与缓存相关的设置。

JSR-107对应

Spring 缓存注解JSR-107备注
@Cacheable@CacheResult相当相似。 可以缓存特定的异常并强制 无论缓存的内容如何,都执行该方法。@CacheResult
@CachePut@CachePut当 Spring 使用方法调用的结果更新缓存时,JCache 要求将其作为注释的参数传递。 由于这种差异,JCache 允许在 实际方法调用。@CacheValue
@CacheEvict@CacheRemove相当相似。 支持有条件逐出,当 方法调用会导致异常。@CacheRemove
@CacheEvict(allEntries=true)@CacheRemoveAll看。@CacheRemove
@CacheConfig@CacheDefaults允许您以类似的方式配置相同的概念。

SpEL上下文数据

名称位置描述示例
methodNameroot对象当前被调用的方法名#root.methodname
methodroot对象当前被调用的方法#root.method.name
targetroot对象当前被调用的目标对象实例#root.target
targetClassroot对象当前被调用的目标对象的类#root.targetClass
argsroot对象当前被调用的方法的参数列表#root.args[0]
cachesroot对象当前方法调用使用的缓存列表#root.caches[0].name
Argument Name执行上下文当前被调用的方法的参数,如findArtisan(Artisan artisan),可以通过#artsian.id获得参数#artsian.id
result执行上下文方法执行后的返回值(仅当方法执行后的判断有效,如 unless cacheEvict的beforeInvocation=false)#result

引入依赖

    implementation 'org.springframework.boot:spring-boot-starter-cache'

添加启用缓存注解@EnableCaching

@SpringBootApplication(scanBasePackages = {"com.kongxiang"})
@EnableAutoConfiguration
@EnableCaching
public class StudySpring3Application {public static void main(String[] args) {SpringApplication.run(StudySpring3Application.class, args);}
}

cache 支持的缓存类型

spring cache支持的缓存类型
查看类org.springframework.boot.autoconfigure.cache.CacheType

public enum CacheType {/*** Generic caching using 'Cache' beans from the context.*/GENERIC,/*** JCache (JSR-107) backed caching.*/JCACHE,/*** Hazelcast backed caching.*/HAZELCAST,/*** Couchbase backed caching.*/COUCHBASE,/*** Infinispan backed caching.*/INFINISPAN,/*** Redis backed caching.*/REDIS,/*** Cache2k backed caching.*/CACHE2K,/*** Caffeine backed caching.*/CAFFEINE,/*** Simple in-memory caching.*/SIMPLE,/*** No caching.*/NONE}

缓存类型配置

NONE

无缓存

spring:cache:type: NONE

SIMPLE

内存缓存

spring:cache:type: SIMPLE

在这里插入图片描述

REDIS

Redis 缓存

spring:cache:type: REDISdata:redis:host: '127.0.0.1'username:port: 6379password:database: 1lettuce:pool:enabled: truemax-active: 8max-wait: 1000max-idle: 8connect-timeout: 5000
自定义配置

默认情况下会有两个模板类被注入Spring IoC供我们使用,需要个性化配置来满足实际的开发。

一个是RedisTemplate<Object, Object>,主要用于对象缓存,其默认使用JDK序列化,我们需要更改其序列化方式解决一些问题,比如Java 8日期问题JSON序列化问题。需要我们重写一下。

  1. RedisTemplate自定义配置
 @Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);// 使用Jackson2JsonRedisSerialize 替换默认序列化Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = initJacksonSerializer();// 设置value的序列化规则和 key的序列化规则template.setValueSerializer(jackson2JsonRedisSerializer);template.setKeySerializer(new StringRedisSerializer());template.afterPropertiesSet();return template;}/*** 处理redis序列化问题* @return Jackson2JsonRedisSerializer*/private Jackson2JsonRedisSerializer<Object> initJacksonSerializer() {ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);//以下替代旧版本 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);//bugFix Jackson2反序列化数据处理LocalDateTime类型时出错om.disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);// java8 时间支持om.registerModule(new JavaTimeModule());return new Jackson2JsonRedisSerializer<>(om,Object.class);}
  1. 缓存管理器自定义配置
    使用Spring Cache做缓存的时候,有针对不同的key设置不同过期时间的场景。比如Jwt Token我想设置为一周过期,而验证码我想设置为五分钟过期。这个怎么实现呢?需要我们个性化配置RedisCacheManager。首先我通过枚举来定义这些缓存及其TTL时间

我们通过向Spring IoC分别注入RedisCacheConfigurationRedisCacheManagerBuilderCustomizer来个性化配置

/*** Redis cache configuration.** @param redisTemplate the redis template* @return the redis cache configuration*/@Beanpublic RedisCacheConfiguration redisCacheConfiguration(RedisTemplate<Object, Object> redisTemplate, CacheProperties cacheProperties) {// 参见 spring.cache.redisCacheProperties.Redis redisProperties = cacheProperties.getRedis();RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()// 缓存的序列化问题.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));if (redisProperties.getTimeToLive() != null) {// 全局 TTL 时间redisCacheConfiguration = redisCacheConfiguration.entryTtl(redisProperties.getTimeToLive());}if (redisProperties.getKeyPrefix() != null) {// key 前缀值redisCacheConfiguration = redisCacheConfiguration.prefixCacheNameWith(redisProperties.getKeyPrefix());}if (!redisProperties.isCacheNullValues()) {// 默认缓存null值 可以防止缓存穿透redisCacheConfiguration = redisCacheConfiguration.disableCachingNullValues();}if (!redisProperties.isUseKeyPrefix()) {// 不使用key前缀redisCacheConfiguration = redisCacheConfiguration.disableKeyPrefix();}return redisCacheConfiguration;}/*** Redis cache manager 个性化配置缓存过期时间.** @return the redis cache manager builder customizer*/@Beanpublic RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer(RedisCacheConfiguration redisCacheConfiguration) {return builder -> builder.cacheDefaults(redisCacheConfiguration);}

CAFFEINE

引入依赖

    implementation 'com.github.ben-manes.caffeine:caffeine:3.1.8'

修改配置

spring:cache:type: CAFFEINE

直接启动即可

Hazelcast

总结

spring cache 缓存抽象加上spring data包和spring boot autoconfig 配置包的能力,可以快速接入一个具体的缓存实现。redis是我们公司基本使用的缓存策略。所以针对redis的一些自定义配置,通过 java bean的方式实现。着重强调一下。

相关文章:

【7】Spring Boot 3 集成组件:缓存组件 spring cache + spring data redis

目录 【7】Spring Boot 3 集成组件&#xff1a;缓存组件 spring cache spring data redis什么是缓存抽象声明式注解JSR-107对应SpEL上下文数据 引入依赖cache 支持的缓存类型缓存类型配置NONESIMPLEREDIS自定义配置 CAFFEINE Hazelcast...总结 个人主页: 【⭐️个人主页】 需要…...

说说Java中的不可重入锁

什么是锁&#xff1f; 简单来讲在Java中&#xff0c;锁是一种用于并发控制的机制&#xff0c;用于保护共享资源&#xff0c;防止多个线程同时访问或修改数据导致的数据不一致性和线程安全问题。在Java虚拟机&#xff08;JVM&#xff09;中&#xff0c;每个对象都有一个相关联的…...

C++学习 --vector

目录 1&#xff0c; 什么是vector 2&#xff0c; 创建vector 2-1&#xff0c; 标准数据类型 2-2&#xff0c; 自定义数据类型 2-3&#xff0c; 其他创建方式 3&#xff0c; 操作vector 3-1&#xff0c; 赋值 3-2&#xff0c; 添加元素 3-2-1&#xff0c; 添加元素(assi…...

Android图片涂鸦,Kotlin(1)

Android图片涂鸦&#xff0c;Kotlin&#xff08;1&#xff09; import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.graphics.PointF import android.…...

upload-labs(1-17关攻略详解)

upload-labs pass-1 上传一个php文件&#xff0c;发现不行 但是这回显是个前端显示&#xff0c;直接禁用js然后上传 f12禁用 再次上传&#xff0c;成功 右键打开该图像 即为位置&#xff0c;使用蚁剑连接 连接成功 pass-2 源码 $is_upload false; $msg null; if (isse…...

《 机器人基础 》期末试卷(A)

一、填空题&#xff08;30分&#xff0c;每空2分&#xff09; 1. 按照相机的工作方式&#xff0c;机器人常用相机分为1&#xff09;__ 单目摄像头 2&#xff09;__ 双目摄像头 _ 3&#xff09;_深度摄像头_ 三类。 2. 度量地图强调…...

Azure Machine Learning - Azure AI 搜索中的矢量搜索

矢量搜索是一种信息检索方法&#xff0c;它使用内容的数字表示形式来执行搜索方案。 由于内容是数字而不是纯文本&#xff0c;因此搜索引擎会匹配与查询最相似的矢量&#xff0c;而不需要匹配确切的字词。本文简要介绍了 Azure AI 搜索中的矢量支持。 其中还解释了与其他 Azure…...

3 redis实现一个消息中间件

使用list实现一个队列&#xff0c;可以从左侧入队&#xff0c;也可以从右侧入对 即可以从左侧读取&#xff0c;也可以从右侧读取 1、Lindex Lindex 命令用于通过索引获取列表中的元素 也可以使用负数下标&#xff0c;以 -1 表示列表的最后一个元素&#xff0c; -2 表示列表的…...

js添加dom到指定div之后,并给添加的dom类名,然后设置其样式,以及el-popover层级z-index过高问题解决。

遇到一个需求,Vue项目做一个表格,要求表头与表格内容分开,如下效果所示,表头与表格有个高度间隔边距(箭头所示),因为默认我们的el-table的表头与内容是一起的: 思路:通过querySelector获取el-table__header-wrapper元素,通过createElement创建一个div,通过 newElem…...

C语言结构体

#include <stdio.h> #include <string.h> #include <stdlib.h>//struct Student_s { // int num; // char name[20]; // char gender; // int age; // float Chinese; // float Math; // float English; // char addr[30]; //}; //最后的分号一定要写&#x…...

【Python大数据笔记_day10_Hive调优及Hadoop进阶】

hive调优 hive官方配置url: Configuration Properties - Apache Hive - Apache Software Foundation hive命令和参数配置 hive参数配置的意义: 开发Hive应用/调优时&#xff0c;不可避免地需要设定Hive的参数。设定Hive的参数可以调优HQL代码的执行效率&#xff0c;或帮助定位问…...

React经典初级错误

文章 前言错误场景问题分析解决方案后言 前言 ✨✨ 他们是天生勇敢的开发者&#xff0c;我们创造bug&#xff0c;传播bug&#xff0c;毫不留情地消灭bug&#xff0c;在这个过程中我们创造了很多bug以供娱乐。 前端bug这里是博主总结的一些前端的bug以及解决方案&#xff0c;感兴…...

C# System.Array.CopyTo() 和 System.Array.Clone() 有什么区别

System.Array.CopyTo() 和 System.Array.Clone() 是用于数组复制的两种不同方法&#xff0c;它们在实现和用途上有一些区别。 System.Array.CopyTo() 方法&#xff1a; CopyTo() 方法用于将数组的元素复制到另一个数组。它是 Array 类的实例方法&#xff0c;可以用于复制一个…...

Stable Diffusion 启动时 got an unexpected keyword argument ‘socket_options‘ 错误解决

Stable Diffusion 启动时 got an unexpected keyword argument socket_options 错误解决 问题解决方法 问题 Launching Web UI with arguments: Traceback (most recent call last):File "launch.py", line 48, in <module>main()File "launch.py"…...

CSS 文本属性篇

文字颜色 属性名&#xff1a;color作用&#xff1a;控制文字的颜色可选值&#xff1a; 1.颜色名 color: blue; 2.rgb或rgba color:rgb(132, 220, 254); color:rgba(132, 220, 254,0.5); 3.hex或hexa&#xff08;十六进制&#xff09; color:#0078d4; color:#0078d48b; 4.hsl或h…...

Activiti,Apache camel,Netflex conductor对比,业务选型

Activiti,Apache camel,Netflex conductor对比&#xff0c;业务选型 1.activiti是审批流&#xff0c;主要应用于人->系统交互&#xff0c;典型应用场景&#xff1a;请假&#xff0c;离职等审批 详情可见【精选】activti实际使用_activiti通过事件监听器实现的优势_记录点滴…...

pythom导出mysql指定binlog文件

要求 要求本地有py环境和全局环境变量 先测试直接执行binlog命令执行命令 Windows 本地直接执行命令 # E:\output>E:\phpstudy_pro\Extensions\MySQL5.7.26\bin\mysqlbinlog binglog文件地址 # --no-defaults 不限制编码 # -h mysql链接地址 # -u mysql 链接名称 # -p m…...

TDengine 跨版本迁移实战

TDengine 3.0 已经退出了近一年&#xff0c;目前已经到了 3.2 版本。很遗憾的是 2.x 和 3.x 之间的数据文件不兼容。 如果向从 2.x 升级到 3.x 只能选择数据迁移的方式。 目前数据迁移有三种方法&#xff1a; 使用官方推荐工具 taosx。使用 taosdump 工具。自己写程序。 迁移…...

FPGA设计时序约束八、others类约束之Set_Case_Analysis

目录 一、序言 二、Set Case Analysis 2.1 基本概念 2.2 设置界面 2.3 命令语法 2.4 命令示例 三、工程示例 四、参考资料 一、序言 在Vivado的时序约束窗口中&#xff0c;存在一类特殊的约束&#xff0c;划分在others目录下&#xff0c;可用于设置忽略或修改默认的时序…...

xftp连接wsl2

在WSL中默认是没有安装OpenSSH&#xff0c;需要自己安装。 安装 sudo apt update sudo apt install openssh-server检查是否安装成功 ssh -V配置ssh sudo vim /etc/ssh/ssh_config设置端口 Port 22启动ssh服务 sudo service ssh startxftp连接 主机地址&#xff1a;127.…...

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

Ubuntu系统下交叉编译openssl

一、参考资料 OpenSSL&&libcurl库的交叉编译 - hesetone - 博客园 二、准备工作 1. 编译环境 宿主机&#xff1a;Ubuntu 20.04.6 LTSHost&#xff1a;ARM32位交叉编译器&#xff1a;arm-linux-gnueabihf-gcc-11.1.0 2. 设置交叉编译工具链 在交叉编译之前&#x…...

centos 7 部署awstats 网站访问检测

一、基础环境准备&#xff08;两种安装方式都要做&#xff09; bash # 安装必要依赖 yum install -y httpd perl mod_perl perl-Time-HiRes perl-DateTime systemctl enable httpd # 设置 Apache 开机自启 systemctl start httpd # 启动 Apache二、安装 AWStats&#xff0…...

【项目实战】通过多模态+LangGraph实现PPT生成助手

PPT自动生成系统 基于LangGraph的PPT自动生成系统&#xff0c;可以将Markdown文档自动转换为PPT演示文稿。 功能特点 Markdown解析&#xff1a;自动解析Markdown文档结构PPT模板分析&#xff1a;分析PPT模板的布局和风格智能布局决策&#xff1a;匹配内容与合适的PPT布局自动…...

DIY|Mac 搭建 ESP-IDF 开发环境及编译小智 AI

前一阵子在百度 AI 开发者大会上&#xff0c;看到基于小智 AI DIY 玩具的演示&#xff0c;感觉有点意思&#xff0c;想着自己也来试试。 如果只是想烧录现成的固件&#xff0c;乐鑫官方除了提供了 Windows 版本的 Flash 下载工具 之外&#xff0c;还提供了基于网页版的 ESP LA…...

[Java恶补day16] 238.除自身以外数组的乘积

给你一个整数数组 nums&#xff0c;返回 数组 answer &#xff0c;其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法&#xff0c;且在 O(n) 时间复杂度…...

select、poll、epoll 与 Reactor 模式

在高并发网络编程领域&#xff0c;高效处理大量连接和 I/O 事件是系统性能的关键。select、poll、epoll 作为 I/O 多路复用技术的代表&#xff0c;以及基于它们实现的 Reactor 模式&#xff0c;为开发者提供了强大的工具。本文将深入探讨这些技术的底层原理、优缺点。​ 一、I…...

Typeerror: cannot read properties of undefined (reading ‘XXX‘)

最近需要在离线机器上运行软件&#xff0c;所以得把软件用docker打包起来&#xff0c;大部分功能都没问题&#xff0c;出了一个奇怪的事情。同样的代码&#xff0c;在本机上用vscode可以运行起来&#xff0c;但是打包之后在docker里出现了问题。使用的是dialog组件&#xff0c;…...

保姆级教程:在无网络无显卡的Windows电脑的vscode本地部署deepseek

文章目录 1 前言2 部署流程2.1 准备工作2.2 Ollama2.2.1 使用有网络的电脑下载Ollama2.2.2 安装Ollama&#xff08;有网络的电脑&#xff09;2.2.3 安装Ollama&#xff08;无网络的电脑&#xff09;2.2.4 安装验证2.2.5 修改大模型安装位置2.2.6 下载Deepseek模型 2.3 将deepse…...

Python网页自动化Selenium中文文档

1. 安装 1.1. 安装 Selenium Python bindings 提供了一个简单的API&#xff0c;让你使用Selenium WebDriver来编写功能/校验测试。 通过Selenium Python的API&#xff0c;你可以非常直观的使用Selenium WebDriver的所有功能。 Selenium Python bindings 使用非常简洁方便的A…...