一、什么是Spring Cache

从spring 3.1版本开始,提供了一种透明的方式来为现有的spring 应用添加cache。在应用层面与后端存储之间,提供了一层抽象,这层抽象目的在于封装各种可插拔的后端存储( ehcache guava redis),最小化因为缓存给现有业务代码带来的侵入。

核心抽象主要体现在两个接口上
org.springframework.cache.cache

org.springframework.cache.cachemanager

cache代表缓存本身,包含缓存的常用操作:增加、删除、读取等。

CacheManager 是 Spring 各种缓存的抽象接口。抽象的意义在于屏蔽实现细节的差异和提供扩展性,这一层cache的抽象解耦了缓存的使用和缓存的后端存储,这样后续可以方便的更换后端存储。

Spring 支持的常用 CacheManager 如下:

CacheManager 描述
SimpleCacheManager 使用简单的 Collection 来存储缓存
ConcurrentMapCacheManager 使用 java.util.ConcurrentHashMap 来实现缓存
NoOpCacheManager 仅测试用,不会实际存储缓存
EhCacheCacheManger 使用EhCache作为缓存技术。EhCache 是一个纯 Java 的进程内缓存框架,特点快速、精干,是 Hibernate 中默认的 CacheProvider,也是 Java 领域应用最为广泛的缓存
JCacheCacheManager 支持JCache(JSR-107)标准的实现作为缓存技术
CaffeineCacheManager 使用 Caffeine 作为缓存技术。用于取代 Guava 缓存技术。
RedisCacheManager 使用Redis作为缓存技术
HazelcastCacheManager 使用Hazelcast作为缓存技术
CompositeCacheManager 用于组合 CacheManager,可以从多个 CacheManager 中轮询得到相应的缓存

二、核心注解

Spring Cache 提供了 @Cacheable 、@CachePut 、@CacheEvict 、@Caching 等注解

1、 @Cacheable

缓存数据或者获取缓存数据

属性值如下:

属性/方法名 解释
value 缓存名,必填,它指定了你的缓存存放在哪块命名空间
cacheNames 与 value 差不多,二选一即可
key 可选属性,可以使用 SpEL 标签自定义缓存的key
keyGenerator key的生成器。key/keyGenerator二选一使用
cacheManager 指定缓存管理器
cacheResolver 指定获取解析器
condition 条件符合则缓存
unless 条件符合则不缓存
sync 是否使用异步模式,默认为false

2、@CachePut

修改缓存数据。

属性/方法名 解释
value 缓存名,必填,它指定了你的缓存存放在哪块命名空间
cacheNames 与 value 差不多,二选一即可
key 可选属性,可以使用 SpEL 标签自定义缓存的key
keyGenerator key的生成器。key/keyGenerator二选一使用
cacheManager 指定缓存管理器
cacheResolver 指定获取解析器
condition 条件符合则缓存
unless 条件符合则不缓存

3、@EnableCaching

开启缓存功能,一般放在启动类上

4、@CacheEvict

清空缓存

属性/方法名 解释
value 缓存名,必填,它指定了你的缓存存放在哪块命名空间
cacheNames 与 value 差不多,二选一即可
key 可选属性,可以使用 SpEL 标签自定义缓存的key
keyGenerator key的生成器。key/keyGenerator二选一使用
cacheManager 指定缓存管理器
cacheResolver 指定获取解析器
condition 条件符合则缓存
allEntries 是否清空所有缓存,默认为 false。如果指定为 true,则方法调用后将立即清空所有的缓存
beforeInvocation 是否在方法执行前就清空,默认为 false。如果指定为 true,则在方法执行前就会清空缓存

5、@Caching

该注解可以实现同一个方法上同时使用多种注解。

6、@CacheConfig

统一配置@Cacheable中的value值

三、接入Redis简单案例demo

1、添加maven依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>${version}</version>
</dependency>

2、redis配置

spring:redis:# Redis数据库索引(默认为0)database: 0host: 127.0.0.1password: test# Redis服务器连接端口port: 6379# 连接超时时间(毫秒)timeout: 10000jedis:pool:# 连接池最大连接数(使用负值表示没有限制)max-active: 8# 连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: -1# 连接池中的最大空闲连接max-idle: 8# 连接池中的最小空闲连接min-idle: 0

3、配置CacheManager以及自定义key生成策略

@EnableConfigurationProperties(CacheProperties.class)
@Configuration(proxyBeanMethods = false)
public class RedisCacheAutoConfiguration extends CachingConfigurerSupport {@Resourceprivate RedisConnectionFactory factory;@Resourceprivate CacheProperties cacheProperties;/*** 自定义生成redis-key*/@Override@Primary@Beanpublic KeyGenerator keyGenerator() {return (target, method, params) -> {StringBuilder sb = new StringBuilder(cacheProperties.getCacheKeyPrefix()).append(":");sb.append(target.getClass().getName()).append(":");sb.append(method.getName()).append(":");for (Object param : params) {sb.append(param.toString()).append(":");}return sb.toString();};}@Override@Bean@Primarypublic CacheResolver cacheResolver() {return new SimpleCacheResolver(cacheManager());}/*** 配置CacheManager*/@Primary@Bean@Overridepublic CacheManager cacheManager() {RedisCacheConfiguration defaultRedisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()//不缓存null结果
//                .disableCachingNullValues().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer(CommonUtil.objectMapper())))//默认缓存30分钟.entryTtl(Duration.ofMinutes(30))//设置缓存key前缀.computePrefixWith(cacheKeyPrefix());return new CustomRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(factory), defaultRedisCacheConfiguration);}/*** key添加默认前缀方法*/@Primary@Beanpublic CacheKeyPrefix cacheKeyPrefix() {return (String cacheName) -> {String[] arr = cacheName.split(CustomRedisCacheManager.SEPARATOR);StringBuilder sb = new StringBuilder(cacheProperties.getCacheKeyPrefix()).append(":").append(arr[0]).append(":");return sb.toString();};}}

默认key前缀配置

@Data
@ConfigurationProperties(prefix = "test.cache")
public class CacheProperties {/*** 缓存key前缀*/private String cacheKeyPrefix;}

自定义RedisCacheManager用于重写过期时间

/*** 继承RedisCacheManager,重写createRedisCache方法,定义缓存过期时间*/
public class CustomRedisCacheManager extends RedisCacheManager {public static final String SEPARATOR = "#";public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {super(cacheWriter, defaultCacheConfiguration);}@Overrideprotected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {String[] arr = StringUtils.delimitedListToStringArray(name, SEPARATOR);name = arr[0];if (arr.length > 1) {// 缓存过期时间,注意单位是秒long ttl = Long.parseLong(arr[1]);cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));}return super.createRedisCache(name, cacheConfig);}
}

使用案例

    //缓存失效时间1800s,key为拼接nick@Cacheable(value = "taoOrderAnalysis#1800", key = "#nick")public TaoOrderAnalysisDianzhang queryByNick(String nick) {TableRouter tableRouter = new TableRouter();tableRouter.setDbNo(1);tableRouter.setLogicTable("tao_order_analysis_dianzhang");return taoOrderAnalysisDianzhangMapper.queryByNick(nick, tableRouter);}

在传递的nick为 -fengye- ,定义的cacheKeyPrefix为 test ,那么获取缓存使用key为:test:taoOrderAnalysis:-fengye-

Spring Cache使用Redis自定义缓存key相关推荐

  1. 22-08-06 西安 尚医通(03)EasyExcel; Spring Cache 、Redis做缓存

    EasyExcel EasyExcel:一行一行读取到内存 EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单.节省内存著称 POI:java里操作excel,读取.创建excel ...

  2. springboot整合spring @Cache和Redis

    转载自  springboot整合spring @Cache和Redis spring基于注解的缓存 对于缓存声明,spring的缓存提供了一组java注解: @Cacheable:触发缓存写入. @ ...

  3. Spring Boot 集成 Redis 实现缓存机制

    本文章牵涉到的技术点比较多:spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对以上这些技术点有一定的了解或者也可以先看看这篇文章 ...

  4. Spring Boot 2 + Redis 对象缓存

    依赖配置 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http:/ ...

  5. SpringBoot 结合 Spring Cache 操作 Redis 实现数据缓存

    点击上方"后端技术精选",选择"置顶公众号" 技术文章第一时间送达! 作者:超级小豆丁 http://www.mydlq.club/article/55/ 系统 ...

  6. Spring Boot 整合Redis 实现缓存

    本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解 运行环境 ...

  7. Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 一.缓 ...

  8. 关于Spring Boot + Mybatis + Redis二级缓存整合详解

    二级缓存是多个SqlSession共享的,其作用域是mapper的同一个namespace,不同的sqlSession两次执行相同namespace下的sql语句且向sql中传递参数也相同即最终执行相 ...

  9. Java Web现代化开发:Spring Boot + Mybatis + Redis二级缓存

    背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybatis是一个十分轻量好用的ORM框架.Redis是当今十分主流的分布式key- ...

最新文章

  1. Transformer全靠数据堆?那没有数据怎么办?LUT告诉你「冇问题」|AAAI 2021
  2. c语言double变量后面几个0,C语言double型变量的初始化到底是是0还是0.0?
  3. crontab中执行postgresql命令
  4. vue 分模块打包 脚手架_一步步从头搭建 Vue 开发环境
  5. 第一个servlet小程序
  6. Interview Common Sample Codes
  7. 通过jdbc的mysql驱动连接oceanbase mysql模式数据库
  8. oracle环境变量怎么配,oracle环境变量配置-Oracle
  9. jupyter 代码到 pycharm 的迁移
  10. 3.Magento的布局(Layout),块(Block)和模板(Template)
  11. 2017CV技术报告:从3D物体重建到人体姿态估计
  12. 织梦php 文章采集规则,dede自带采集器的高阶技巧
  13. 用Python做数据分析告诉你奶茶哪家最好喝性价比最高?
  14. 三文鱼肉质和虹鳟鱼肉质有什么区别差异
  15. 用vba创建图表分析上市公司财报
  16. 云服务器无法远程连接常见原因如下:
  17. SELinux/SEAndroid -- 基础知识介绍
  18. Windows 使用键盘移动窗口
  19. 华为云计算之华为私有云初识
  20. android APP读写execl文件,文件管理器查看excel文件

热门文章

  1. 华为ENSP模拟器简易路由交换机分段划分Vlan
  2. Windows查看及修改tomcat端口
  3. Fisherface(FLD)人脸识别实验
  4. 高通量测序中常见名词解释
  5. HashMap源码阅读笔记
  6. 【STM32系列汇总】博主的STM32实战快速进阶之路(持续更新)
  7. 介孔二氧化硅纳米球 Mesoporous silica nanosphere 的介孔二氧化硅纳米球
  8. 匈牙利命名法Hungarian Notation
  9. 无人驾驶小车调试笔记(三)--小车启动及初始化设置
  10. 如何学习一门计算机语言(续)