SpringCache
Spring 从3.1 开始定义了org.springframework.cache.Cache
和org.springframework.cache.CacheManager 接口来统一不同的缓存技术;
并支持使用JCache(JSR-107)注解简化我们开发;
Cache 接口为缓存的组件规范定义,包含缓存的各种操作集合; Cache 接口下Spring 提供了各种xxxCache 的实现;
如RedisCache , EhCacheCache , ConcurrentMapCache 等;
每次调用需要缓存功能的方法时,Spring 会检查检查指定参数的指定的目标方法是否已
经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓
存结果后返回给用户。下次调用直接从缓存中获取。
CacheManager 缓存管理器
public interface CacheManager {//根据缓存名字获取缓存@NullableCache getCache(String name);//获取管理的所有缓存的名字Collection<String> getCacheNames();}
支持多种类型的缓存
整合SpringCache
<!-- 引入spring-boot-starter-cache --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>
这里我们使用redis作为缓存
<!-- 引入redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency><!-- jedis不写版本springboot控制 --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency>
配置spring-boot-starter-cache
1.缓存的自动配置
CacheProperties封装了配置文件中可以配置的属性
@ConfigurationProperties(prefix = "spring.cache")
org.springframework.boot.autoconfigure.cache.CacheProperties
CacheConfiguration
会根据缓存类型导入RedisCacheConfiguration
RedisCacheConfiguration
自动配好了缓存管理器
@Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory,ResourceLoader resourceLoader) {RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(determineConfiguration(resourceLoader.getClassLoader()));List<String> cacheNames = this.cacheProperties.getCacheNames();if (!cacheNames.isEmpty()) {builder.initialCacheNames(new LinkedHashSet<>(cacheNames));}return this.customizerInvoker.customize(builder.build());}
手动配置
配置使用Redis作为缓存
spring:cache:#cache-names: 可以自动配置type: redis
测试使用缓存
常用注解
1.开启缓存功能 @Cacheable({"…"})
在启动类添加@EnableCaching 注解,不需要重复配Redis
@EnableCaching 注解
2.使用注解 就能完成缓存操作
//每一个需要缓存的数据都需要指定要放到哪个名字的缓存,缓存的分区,按照业务类型分 @Cacheable({"categroy"}) //代表方法的结果需要缓存 ,如果缓存中有 方法都不用调用,如果缓存中没有,调用方法,将结果放入缓存@Overridepublic List<CategoryEntity> getLevel1Categorys() {long l = System.currentTimeMillis();List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));System.out.println("消耗时间:" + (System.currentTimeMillis() - l));return categoryEntityList;}
使用@Cacheable 默认行为
如果缓存中有缓存 方法都不用调用
key值 自动生成
缓存的Value值默认使用JDK序列化机制,将序列化后的数据存到Redis
默认过期时间TTL -1 永不过去
应该要指定缓存存活时间 在配置文件中修改
cache:#cache-names: 可以自动配置type: redisredis:time-to-live: 3600000 #设置存活时间毫秒key-prefix: CACHE_ #key前缀 如果制定了前缀就用指定的前缀,如果没有就默认使用缓存的名字作为前缀use-key-prefix: true # 是否使用前缀cache-null-values: true # 是否缓存控制 解决缓存穿透
应该要指定缓存的Key 使用key属性 接收SpEL表达式
@Cacheable(value = {"categroy"},key = "#root.method.name")@Cacheable(value = {"categroy"},key = "'name'")
SpEL语法
将数据保存为JSON格式
CacheConfiguration —> RedisCacheConfiguration —> 自动配置了RedisCacheManager —> 初始化所有的缓存 —> 每个缓存决定使用什么配置,配置有就用配置的,配置没有就用默认的(key的前缀等)—>想要修改配置只需要在容器中放一个RedisCacheConfiguration 即可 —> 这个容器就会应用到当前RedisCacheManager 管理的所有缓存分区中
package cn.cloud.xmall.product.config;import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @Description: ···* @author: Freedom* @QQ: 1556507698* @date:2022/3/17 13:26*/@EnableCaching
@Configuration
public class MyCacheConfig {@BeanRedisCacheConfiguration redisCacheConfiguration(){RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();//config = config.entryTtl();//key的序列化config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));//值的序列化config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));return config;};}
问题:
配置文件中的东西没有用上
原因 :
使用我们自己的配置不会从配置文件中取出来配置
package cn.cloud.xmall.product.config;import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @Description: ···* @author: Freedom* @QQ: 1556507698* @date:2022/3/17 13:26*/@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {// @Autowired// public CacheProperties cacheProperties;/*** 配置文件的配置没有用上* @return*/@Beanpublic RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();// config = config.entryTtl();//设置Key的序列化方式config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));//设置值的序列化方式config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));CacheProperties.Redis redisProperties = cacheProperties.getRedis();//将配置文件中所有的配置都生效if (redisProperties.getTimeToLive() != null) {config = config.entryTtl(redisProperties.getTimeToLive());}if (redisProperties.getKeyPrefix() != null) {config = config.prefixKeysWith(redisProperties.getKeyPrefix());}if (!redisProperties.isCacheNullValues()) {config = config.disableCachingNullValues();}if (!redisProperties.isUseKeyPrefix()) {config = config.disableKeyPrefix();}return config;}}
从缓存中删除数据 @CacheEvict 失效模式
@CacheEvict(value = "category",key = "'getLevel1Categorys'")
分区value和key必须相同才可以删除
问题:
如果一个修改需要删除两个缓存?如何删除?
@CaChing 组合操作,同时进行多个缓存操作
@Caching(evict = {@CacheEvict(value = "category",key = "'getLevel1Categorys'"),@CacheEvict(value = "category",key = "'getCatalogJson'")})@Transactional@Overridepublic void updateCascade(CategoryEntity category) {this.updateById(category);//更新关联表categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());}
成功删除
第二种方式:
删除指定分区下所有的缓存,存储统一个类型的数据可以指定为同一个分区,分区名默认就是缓存前缀
@CacheEvict(value = {"category"},allEntries = true)
推荐使用@CaChing
@CaChePut 双写模式使用此注解(解决分布式缓存一致性问题)
Spring-Cache不足
- 读模式
缓存穿透:查询一个null数据
解决:缓存null数据,并设置短暂过期时间,
cache-null-values: true # 是否缓存控制 解决缓存穿透, springcache解决方案
缓存击穿:大量并发进来同时查询一个正好过期的数据
解决:加锁 ???
默认情况下是没有加锁的
1.手写添加缓存方法使用Redisson作为分布式锁
2.@Cacheable(value = {“categroy”},key = “#root.method.name”,sync = true),sync只有Cacheable有这个属性
会进入加锁的方法
缓存雪崩: 大量的key同时过期
解决:添加随机时间,指定过期时间 ,time-to-live: 3600000 #设置存活时间毫秒
- 写模式 (缓存与数据库一致)
读写加锁
引入Canal,感知数据库更新去更新缓存数据
读多写多直接去数据库查询
常规数据的缓存(读多,写少,缓存一致性要求不高)就算没有锁,完全可以使用SpringCache, 但是要求数据高的特殊数据,即想要缓存提升他的速度,又想要缓存一致性,特殊设计,读写锁…Canal…一致性。常规数据只要有缓存的过期时间就可以满足需求了
SpringCache相关推荐
- Spring Boot 2.X整合Spring-cache,让你的网站速度飞起来
计算机领域有人说过一句名言:"计算机科学领域的任何问题都可以通过增加一个中间层来解决",今天我们就用Spring-cache给网站添加一层缓存,让你的网站速度飞起来. 本文目录 一 ...
- SpringCache与redis集成,优雅的缓存解决方案
点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源:cnblogs.com/chenkeyu/p/8028781 ...
- Cache系列:spring-cache简单三步快速应用ehcache3.x-jcache缓存(spring4.x)
前言:本项目基于spring4.x构建,使用ehcache3.5.2和JCache(jsr107规范) 一.依赖 除了ehcache和cache-api外,注意引用spring-context-sup ...
- SpringBoot基础系列-SpringCache使用
原创文章,转载请标注出处:<SpringBoot基础系列-SpringCache使用> 一.概述 SpringCache本身是一个缓存体系的抽象实现,并没有具体的缓存能力,要使用Sprin ...
- springboot redis 刷新时间_「SpringBoot实战」SpringCache + Redis实现数据缓存
关注我的微信公众号:后端技术漫谈 不定期推送关于后端开发.爬虫.算法题.数据结构方面的原创技术文章,以及生活中的逸闻趣事. 我目前是一名后端开发工程师.主要关注后端开发,数据安全,网络爬虫,物联网,边 ...
- spring-boot的spring-cache中的扩展redis缓存的ttl和key名
原文地址:spring-boot的spring-cache中的扩展redis缓存的ttl和key名 前提 spring-cache大家都用过,其中使用redis-cache大家也用过,至于如何使用怎么 ...
- SpringBoot+SpringCache+Redis补充
2019独角兽企业重金招聘Python工程师标准>>> 这里新增加一个例子: ` package com.atguigu.cache.service;import com.atgui ...
- SpringCache与Redis
文章目录 SpringCache简介 常⽤注解Cacheable 自定义CacheManager配置和过期时间 自定义缓存KeyGenerator 常用注解CachePut 和 CacheEvict ...
- SpringCache 集成 Redis,这才是优雅的缓存解决方案!
缓存可以说是加速服务响应速度的一种非常有效并且简单的方式.在缓存领域,有很多知名的框架,如EhCache .Guava.HazelCast等. Redis作为key-value型数据库,由于他的这一特 ...
- 怎么查redis 中的 cache_20、springcloud如何使用spring-cache
学了springcloud如何操作数据库进行增删改查,又学了springcloud如何操作reids把数据存储到redis.今天结合数据库操作和reids操作,来看看如何使用SpringCache.S ...
最新文章
- python 逻辑回归
- Python基础教程:变量和注释
- 步进电机控制芯片_STK682/步进电机_STK682-010-E控制芯片 原创中文翻译
- qt_3_Qt开发环境
- jQuery 基本知识详解
- 目标检测(二十三)--DenseBox
- go语言mongdb管道使用
- Cognos SDK 入门教程(一) - Hello Cognos
- UML统一建模语言是什么?
- Java 菜鸟入门 | 常用进制转换
- NoteExpress自定义题录表头显示字段
- 小白spss学习笔记(一)
- 阿里云域名动态解析dns,ddns php定时更新
- 路由之HSRP热备份
- 【每日早报】2019/12/31
- 干货满满 | 不容错过的数据科学入门数学指南
- 北京大学计算机考博英语,2019年北京大学博士英语考题回忆
- Discuz 论坛优化
- 小米8 twrp recovery_小米手机机型怎么刷入脸谱Magisk模块详细教程
- Paper reading (八十六):Normalization of the microbiota in patients after treatment for colonic lesions