• 【Redis】SSM整合Redis&注解式缓存的使用


    🎉🎉欢迎来到我的CSDN主页!🎉🎉

    🏅我是Java方文山,一个在CSDN分享笔记的博主。📚📚

    🌟推荐给大家我的专栏《Redis》。🎯🎯

    👉点击这里,就可以查看我的主页啦!👇👇

    Java方文山的个人主页

    🎁如果感觉还不错的话请给我点赞吧!🎁🎁

    💖期待你的加入,一起学习,一起进步!💖💖

    请添加图片描述

    目录

    一、SSM整合Redis

    1.1.pom配置

    1.2.配置文件spring-redis.xml

    1.3.修改applicationContext.xml

    1.4.配置redis的key生成策略

    二、Redis的注解式开发及应用场景        

    2.1.什么是Redis注解式

    2.2.为什么使用Redis注解式

    2.3.Redis注解式的应用

    ①Cacheable

    ②CachePut

    ③CacheEvict

    2.4.CachePut和Cacheable的区别

    三、Redis中的击穿、穿透、雪崩的三种场景

    3.1.缓存穿透

    1.什么是缓存穿透?

    2.如何解决缓存穿透问题?

    3.2.缓存击穿

    1.什么是缓存击穿?

    2.如何解决缓存击穿问题?

    3.3.缓存雪崩

    1.什么是缓存雪崩?

    2.如何解决缓存雪崩问题?


    一、SSM整合Redis

    1.1.pom配置

    在Maven或Gradle的构建文件中添加Redis相关的依赖。

    注意:resources的配置必须涵盖读取.properties结尾的文件

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>org.examplegroupId>
    6. <artifactId>ssm2artifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <name>ssm2 Maven Webappname>
    10. <url>http://www.example.comurl>
    11. <properties>
    12. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    13. <maven.compiler.source>1.8maven.compiler.source>
    14. <maven.compiler.target>1.8maven.compiler.target>
    15. <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>
    16. <spring.version>5.0.2.RELEASEspring.version>
    17. <mybatis.version>3.4.5mybatis.version>
    18. <mysql.version>5.1.44mysql.version>
    19. <pagehelper.version>5.1.2pagehelper.version>
    20. <mybatis.spring.version>1.3.1mybatis.spring.version>
    21. <commons.dbcp2.version>2.1.1commons.dbcp2.version>
    22. <commons.pool2.version>2.4.3commons.pool2.version>
    23. <log4j2.version>2.9.1log4j2.version>
    24. <junit.version>4.12junit.version>
    25. <servlet.version>4.0.0servlet.version>
    26. <lombok.version>1.18.2lombok.version>
    27. <ehcache.version>2.10.0ehcache.version>
    28. <slf4j-api.version>1.7.7slf4j-api.version>
    29. <redis.version>2.9.0redis.version>
    30. <redis.spring.version>1.7.1.RELEASEredis.spring.version>
    31. properties>
    32. <dependencies>
    33. <dependency>
    34. <groupId>org.springframeworkgroupId>
    35. <artifactId>spring-contextartifactId>
    36. <version>${spring.version}version>
    37. dependency>
    38. <dependency>
    39. <groupId>org.springframeworkgroupId>
    40. <artifactId>spring-ormartifactId>
    41. <version>${spring.version}version>
    42. dependency>
    43. <dependency>
    44. <groupId>org.springframeworkgroupId>
    45. <artifactId>spring-txartifactId>
    46. <version>${spring.version}version>
    47. dependency>
    48. <dependency>
    49. <groupId>org.springframeworkgroupId>
    50. <artifactId>spring-aspectsartifactId>
    51. <version>${spring.version}version>
    52. dependency>
    53. <dependency>
    54. <groupId>org.springframeworkgroupId>
    55. <artifactId>spring-webartifactId>
    56. <version>${spring.version}version>
    57. dependency>
    58. <dependency>
    59. <groupId>org.springframeworkgroupId>
    60. <artifactId>spring-testartifactId>
    61. <version>${spring.version}version>
    62. dependency>
    63. <dependency>
    64. <groupId>org.mybatisgroupId>
    65. <artifactId>mybatisartifactId>
    66. <version>${mybatis.version}version>
    67. dependency>
    68. <dependency>
    69. <groupId>mysqlgroupId>
    70. <artifactId>mysql-connector-javaartifactId>
    71. <version>${mysql.version}version>
    72. dependency>
    73. <dependency>
    74. <groupId>com.github.pagehelpergroupId>
    75. <artifactId>pagehelperartifactId>
    76. <version>${pagehelper.version}version>
    77. dependency>
    78. <dependency>
    79. <groupId>org.mybatisgroupId>
    80. <artifactId>mybatis-springartifactId>
    81. <version>${mybatis.spring.version}version>
    82. dependency>
    83. <dependency>
    84. <groupId>org.apache.commonsgroupId>
    85. <artifactId>commons-dbcp2artifactId>
    86. <version>${commons.dbcp2.version}version>
    87. dependency>
    88. <dependency>
    89. <groupId>org.apache.commonsgroupId>
    90. <artifactId>commons-pool2artifactId>
    91. <version>${commons.pool2.version}version>
    92. dependency>
    93. <dependency>
    94. <groupId>org.apache.logging.log4jgroupId>
    95. <artifactId>log4j-coreartifactId>
    96. <version>${log4j2.version}version>
    97. dependency>
    98. <dependency>
    99. <groupId>org.apache.logging.log4jgroupId>
    100. <artifactId>log4j-apiartifactId>
    101. <version>${log4j2.version}version>
    102. dependency>
    103. <dependency>
    104. <groupId>org.apache.logging.log4jgroupId>
    105. <artifactId>log4j-webartifactId>
    106. <version>${log4j2.version}version>
    107. dependency>
    108. <dependency>
    109. <groupId>junitgroupId>
    110. <artifactId>junitartifactId>
    111. <version>${junit.version}version>
    112. <scope>testscope>
    113. dependency>
    114. <dependency>
    115. <groupId>javax.servletgroupId>
    116. <artifactId>javax.servlet-apiartifactId>
    117. <version>${servlet.version}version>
    118. <scope>providedscope>
    119. dependency>
    120. <dependency>
    121. <groupId>org.projectlombokgroupId>
    122. <artifactId>lombokartifactId>
    123. <version>${lombok.version}version>
    124. <scope>providedscope>
    125. dependency>
    126. <dependency>
    127. <groupId>org.springframeworkgroupId>
    128. <artifactId>spring-webmvcartifactId>
    129. <version>${spring.version}version>
    130. dependency>
    131. <dependency>
    132. <groupId>javax.servlet.jspgroupId>
    133. <artifactId>javax.servlet.jsp-apiartifactId>
    134. <version>2.3.3version>
    135. dependency>
    136. <dependency>
    137. <groupId>jstlgroupId>
    138. <artifactId>jstlartifactId>
    139. <version>1.2version>
    140. dependency>
    141. <dependency>
    142. <groupId>taglibsgroupId>
    143. <artifactId>standardartifactId>
    144. <version>1.1.2version>
    145. dependency>
    146. <dependency>
    147. <groupId>commons-fileuploadgroupId>
    148. <artifactId>commons-fileuploadartifactId>
    149. <version>1.3.3version>
    150. dependency>
    151. <dependency>
    152. <groupId>org.hibernategroupId>
    153. <artifactId>hibernate-validatorartifactId>
    154. <version>6.0.7.Finalversion>
    155. dependency>
    156. <dependency>
    157. <groupId>com.fasterxml.jackson.coregroupId>
    158. <artifactId>jackson-databindartifactId>
    159. <version>2.9.3version>
    160. dependency>
    161. <dependency>
    162. <groupId>com.fasterxml.jackson.coregroupId>
    163. <artifactId>jackson-coreartifactId>
    164. <version>2.9.3version>
    165. dependency>
    166. <dependency>
    167. <groupId>com.fasterxml.jackson.coregroupId>
    168. <artifactId>jackson-annotationsartifactId>
    169. <version>2.9.3version>
    170. dependency>
    171. <dependency>
    172. <groupId>org.apache.shirogroupId>
    173. <artifactId>shiro-coreartifactId>
    174. <version>1.3.2version>
    175. dependency>
    176. <dependency>
    177. <groupId>org.apache.shirogroupId>
    178. <artifactId>shiro-webartifactId>
    179. <version>1.3.2version>
    180. dependency>
    181. <dependency>
    182. <groupId>org.apache.shirogroupId>
    183. <artifactId>shiro-springartifactId>
    184. <version>1.3.2version>
    185. dependency>
    186. <dependency>
    187. <groupId>net.sf.ehcachegroupId>
    188. <artifactId>ehcacheartifactId>
    189. <version>${ehcache.version}version>
    190. dependency>
    191. <dependency>
    192. <groupId>org.slf4jgroupId>
    193. <artifactId>slf4j-apiartifactId>
    194. <version>${slf4j-api.version}version>
    195. dependency>
    196. <dependency>
    197. <groupId>org.slf4jgroupId>
    198. <artifactId>jcl-over-slf4jartifactId>
    199. <version>${slf4j-api.version}version>
    200. <scope>runtimescope>
    201. dependency>
    202. <dependency>
    203. <groupId>org.apache.logging.log4jgroupId>
    204. <artifactId>log4j-slf4j-implartifactId>
    205. <version>${log4j2.version}version>
    206. dependency>
    207. <dependency>
    208. <groupId>redis.clientsgroupId>
    209. <artifactId>jedisartifactId>
    210. <version>${redis.version}version>
    211. dependency>
    212. <dependency>
    213. <groupId>org.springframework.datagroupId>
    214. <artifactId>spring-data-redisartifactId>
    215. <version>${redis.spring.version}version>
    216. dependency>
    217. dependencies>
    218. <build>
    219. <finalName>ssm2finalName>
    220. <resources>
    221. <resource>
    222. <directory>src/main/javadirectory>
    223. <includes>
    224. <include>**/*.xmlinclude>
    225. includes>
    226. resource>
    227. <resource>
    228. <directory>src/main/resourcesdirectory>
    229. <includes>
    230. <include>*.propertiesinclude>
    231. <include>*.xmlinclude>
    232. includes>
    233. resource>
    234. resources>
    235. <pluginManagement>
    236. <plugins>
    237. <plugin>
    238. <groupId>org.apache.maven.pluginsgroupId>
    239. <artifactId>maven-compiler-pluginartifactId>
    240. <version>${maven.compiler.plugin.version}version>
    241. <configuration>
    242. <source>${maven.compiler.source}source>
    243. <target>${maven.compiler.target}target>
    244. <encoding>${project.build.sourceEncoding}encoding>
    245. configuration>
    246. plugin>
    247. <plugin>
    248. <groupId>org.mybatis.generatorgroupId>
    249. <artifactId>mybatis-generator-maven-pluginartifactId>
    250. <version>1.3.2version>
    251. <dependencies>
    252. <dependency>
    253. <groupId>mysqlgroupId>
    254. <artifactId>mysql-connector-javaartifactId>
    255. <version>${mysql.version}version>
    256. dependency>
    257. dependencies>
    258. <configuration>
    259. <overwrite>trueoverwrite>
    260. configuration>
    261. plugin>
    262. <plugin>
    263. <artifactId>maven-clean-pluginartifactId>
    264. <version>3.1.0version>
    265. plugin>
    266. <plugin>
    267. <artifactId>maven-resources-pluginartifactId>
    268. <version>3.0.2version>
    269. plugin>
    270. <plugin>
    271. <artifactId>maven-compiler-pluginartifactId>
    272. <version>3.8.0version>
    273. plugin>
    274. <plugin>
    275. <artifactId>maven-surefire-pluginartifactId>
    276. <version>2.22.1version>
    277. plugin>
    278. <plugin>
    279. <artifactId>maven-war-pluginartifactId>
    280. <version>3.2.2version>
    281. plugin>
    282. <plugin>
    283. <artifactId>maven-install-pluginartifactId>
    284. <version>2.5.2version>
    285. plugin>
    286. <plugin>
    287. <artifactId>maven-deploy-pluginartifactId>
    288. <version>2.8.2version>
    289. plugin>
    290. plugins>
    291. pluginManagement>
    292. build>
    293. project>

    1.2.配置文件spring-redis.xml

    这个配置文件的作用主要用于配置数据源和连接工厂还有配置序列化的用途

    redis.properties

    1. redis.hostName=localhost
    2. redis.port=6379
    3. redis.password=123456
    4. redis.timeout=10000
    5. redis.maxIdle=300
    6. redis.maxTotal=1000
    7. redis.maxWaitMillis=1000
    8. redis.minEvictableIdleTimeMillis=300000
    9. redis.numTestsPerEvictionRun=1024
    10. redis.timeBetweenEvictionRunsMillis=30000
    11. redis.testOnBorrow=true
    12. redis.testWhileIdle=true
    13. redis.expiration=3600

    spring-redis.xml

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:cache="http://www.springframework.org/schema/cache"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/context
    9. http://www.springframework.org/schema/context/spring-context.xsd
    10. http://www.springframework.org/schema/cache
    11. http://www.springframework.org/schema/cache/spring-cache.xsd">
    12. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    13. <property name="maxIdle" value="${redis.maxIdle}"/>
    14. <property name="maxTotal" value="${redis.maxTotal}"/>
    15. <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
    16. <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
    17. <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
    18. <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
    19. <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    20. <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
    21. bean>
    22. <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
    23. destroy-method="destroy">
    24. <property name="poolConfig" ref="poolConfig"/>
    25. <property name="hostName" value="${redis.hostName}"/>
    26. <property name="port" value="${redis.port}"/>
    27. <property name="password" value="${redis.password}"/>
    28. <property name="timeout" value="${redis.timeout}"/>
    29. bean>
    30. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    31. <property name="connectionFactory" ref="connectionFactory"/>
    32. <property name="keySerializer">
    33. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    34. property>
    35. <property name="valueSerializer">
    36. <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    37. property>
    38. <property name="hashKeySerializer">
    39. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    40. property>
    41. <property name="hashValueSerializer">
    42. <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    43. property>
    44. <property name="enableTransactionSupport" value="true"/>
    45. bean>
    46. <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
    47. <constructor-arg name="redisOperations" ref="redisTemplate"/>
    48. <property name="defaultExpiration" value="${redis.expiration}"/>
    49. <property name="usePrefix" value="true"/>
    50. <property name="cachePrefix">
    51. <bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix">
    52. <constructor-arg index="0" value="-cache-"/>
    53. bean>
    54. property>
    55. bean>
    56. <bean id="cacheKeyGenerator" class="com.zking.ssm.redis.CacheKeyGenerator">bean>
    57. <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
    58. beans>

    1.3.修改applicationContext.xml

    如果spring配置文件中需要配置两个及以上的properties文件则需要在applicationContext.xml中进行配置处理,否则会出现覆盖的情况。

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    5. xmlns:aop="http://www.springframework.org/schema/aop"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    7. <bean id="propertyConfigurer"
    8. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    9. <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    10. <property name="ignoreResourceNotFound" value="true" />
    11. <property name="locations">
    12. <list>
    13. <value>classpath:jdbc.propertiesvalue>
    14. <value>classpath:redis.propertiesvalue>
    15. list>
    16. property>
    17. bean>
    18. <import resource="applicationContext-mybatis.xml">import>
    19. <import resource="spring-redis.xml">import>
    20. <import resource="applicationContext-shiro.xml">import>
    21. beans>

    1.4.配置redis的key生成策略

    CacheKeyGenerator.java

    1. package com.zking.ssm.redis;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.cache.interceptor.KeyGenerator;
    4. import org.springframework.util.ClassUtils;
    5. import java.lang.reflect.Array;
    6. import java.lang.reflect.Method;
    7. @Slf4j
    8. public class CacheKeyGenerator implements KeyGenerator {
    9. // custom cache key
    10. public static final int NO_PARAM_KEY = 0;
    11. public static final int NULL_PARAM_KEY = 53;
    12. @Override
    13. public Object generate(Object target, Method method, Object... params) {
    14. StringBuilder key = new StringBuilder();
    15. key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");
    16. if (params.length == 0) {
    17. key.append(NO_PARAM_KEY);
    18. } else {
    19. int count = 0;
    20. for (Object param : params) {
    21. if (0 != count) {//参数之间用,进行分隔
    22. key.append(',');
    23. }
    24. if (param == null) {
    25. key.append(NULL_PARAM_KEY);
    26. } else if (ClassUtils.isPrimitiveArray(param.getClass())) {
    27. int length = Array.getLength(param);
    28. for (int i = 0; i < length; i++) {
    29. key.append(Array.get(param, i));
    30. key.append(',');
    31. }
    32. } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
    33. key.append(param);
    34. } else {//Java一定要重写hashCode和eqauls
    35. key.append(param.hashCode());
    36. }
    37. count++;
    38. }
    39. }
    40. String finalKey = key.toString();
    41. // IEDA要安装lombok插件
    42. log.debug("using cache key={}", finalKey);
    43. return finalKey;
    44. }
    45. }

    具体生成缓存键的逻辑如下:

    1. 首先,将目标对象的简单类名和方法名添加到缓存键中,以方便区分不同的方法。
    2. 接下来,根据方法的参数个数进行判断:
      • 如果参数个数为0,则将NO_PARAM_KEY添加到缓存键中,表示没有参数。
      • 如果参数个数大于0,则遍历参数数组,根据参数的类型和取值来生成缓存键的一部分。
    3. 在遍历参数数组时,判断参数的类型:
      • 如果参数为null,则将NULL_PARAM_KEY添加到缓存键中,表示参数为null。
      • 如果参数为基本类型数组,则遍历数组中的元素,并将每个元素及其索引添加到缓存键中。
      • 如果参数为基本类型或包装类类型,或者是字符串类型,则直接将参数添加到缓存键中。
      • 如果参数为其他类型,则使用参数对象的哈希码作为缓存键的一部分。
    4. 最后,将生成的缓存键转换成字符串,并返回。

    在代码中,通过log.debug()语句输出了生成的缓存键,方便调试和查看。

    注意事项:

    • 为了保证缓存键的唯一性,需要确保目标对象、方法以及参数的哈希码等逻辑正确。可以通过重写对象的hashCode()equals()方法来确保哈希码的正确性。
    • 在使用自定义的缓存键生成器时,需要将其配置为Spring缓存注解的keyGenerator属性的值,以替代默认的缓存键生成器。

    二、Redis的注解式开发及应用场景        

    2.1.什么是Redis注解式

    Redis的注解式是指通过使用Spring框架提供的缓存注解,在业务代码中对Redis进行读写操作的方式。这种方式可以大大简化开发人员对缓存的操作,避免了手动编写Redis API代码的繁琐操作。

    Spring框架提供了一系列缓存注解,其中常用的有:

    1. @Cacheable: 表示方法的返回值可以被缓存,如果缓存中已经存在相同Key的值,则直接返回缓存中的值,否则会执行方法体中的代码,并将返回值存储到缓存中。

    2. @CachePut: 表示将方法的返回值存储到缓存中,常用于更新缓存中的值。

    3. @CacheEvict: 表示从缓存中删除指定的Key,常用于删除缓存中的某个值。

    4. @Caching: 表示对多个缓存注解进行组合,常用于同时使用多个注解的场景。

    5. @CacheConfig: 可以在类级别上设置缓存相关的配置,避免在每个方法上重复设置。

    通过使用这些缓存注解,开发人员可以快速方便地实现对Redis的读写操作,同时也能够灵活地控制缓存的过期时间、缓存Key的生成规则等。

    2.2.为什么使用Redis注解式

    使用缓存注解的主要目的是为了提高应用程序的性能和响应速度。当应用程序从数据库或其他资源中获取数据时,如果这些数据在未来的请求中可能会被多次读取,那么使用缓存可以显著减少每个请求的响应时间。缓存将数据存储在内存中,因此可以快速读取,而不需要每次都访问数据库或其他资源。

    使用缓存注解还可以减少对数据库或其他资源的负载,从而减少应用程序的资源消耗。当数据被缓存时,应用程序不需要每次都访问数据库或其他资源,从而减轻了这些资源的负载。

    在使用缓存注解时,需要注意该注解的生命周期和缓存策略。缓存的生命周期指定了数据在缓存中存储的时间,而缓存策略则指定了何时应将数据从缓存中删除。通过选择适当的生命周期和缓存策略,可以优化缓存的性能和效率。

    总之,使用缓存注解可以显著提高应用程序的性能和响应速度,减少对数据库或其他资源的负载,并优化缓存的性能和效率。

    2.3.Redis注解式的应用

    首先搞一个test类来进行讲解

    1. package com.zking.ssm.biz;
    2. import com.zking.ssm.model.Clazz;
    3. import com.zking.ssm.util.PageBean;
    4. import org.springframework.cache.annotation.CacheEvict;
    5. import org.springframework.cache.annotation.CachePut;
    6. import java.util.List;
    7. import java.util.Map;
    8. public interface ClazzBiz {
    9. @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    10. int deleteByPrimaryKey(Integer cid);
    11. int insert(Clazz record);
    12. int insertSelective(Clazz record);
    13. // xx=cache-cid:1
    14. // key的作用改变原有的key生成规则
    15. // @Cacheable(value = "xx",key = "'cid:'+#cid")
    16. @CachePut(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
    17. Clazz selectByPrimaryKey(Integer cid);
    18. int updateByPrimaryKeySelective(Clazz record);
    19. int updateByPrimaryKey(Clazz record);
    20. List listPager(Clazz clazz, PageBean pageBean);
    21. List listMapPager(Clazz clazz, PageBean pageBean);
    22. }

    ①Cacheable

    使用该注解会将查询结果放入Redis中下一次同样的查询就不会走数据库,而是走Redis.

    1. @Cacheable(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
    2. Clazz selectByPrimaryKey(Integer cid);

    value:缓存位置的一段名称,不能为空
    key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
    condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL 

    ②CachePut

    该注解会将查询结果放入Redis中,类似于更新操作,即每次不管缓存中有没有结果,都从数据库查找结果,并将结果更新到缓存,并返回结果

    1. @CachePut(value = "xx",key = "'cid:'+#cid")
    2. Clazz selectByPrimaryKey(Integer cid);

    value:缓存的名称,在 spring 配置文件中定义,必须指定至少一个
    key:缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
    condition:缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存

    ③CacheEvict

    用来清除用在本方法或者类上的缓存数据

    1. @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    2. int deleteByPrimaryKey(Integer cid);

    value:缓存位置的一段名称,不能为空
    key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
    condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL
    allEntries:true表示清除value中的全部缓存,默认为false

    2.4.CachePut和Cacheable的区别

    Cacheable和CachePut都是Spring框架中用于缓存的注解,它们的主要区别是:

    1. Cacheable用于获取缓存中的数据,如果缓存不存在,就会执行方法并将返回值放入缓存中;而CachePut用于更新缓存中的数据,它每次都会执行方法,并将返回值放入缓存中。

    2. Cacheable和CachePut的key生成方式不同,Cacheable默认使用方法的参数作为key,可以通过key属性指定key的生成方式或使用SpEL表达式自定义key的生成方式;而CachePut默认使用Cacheable的默认key生成方式,也可以通过key属性指定key的生成方式。

    3. Cacheable和CachePut的Sync属性也不同,Cacheable默认为false,即异步处理;而CachePut默认为true,即同步处理。

    因此,Cacheable适用于需要从缓存中获取数据的场景,比如读取数据库中的数据;而CachePut适用于需要更新缓存中的数据的场景,比如写入数据库或者删除数据。

    在具体应用场景中,可以根据实际需求选择合适的注解。例如,当我们需要查询用户信息时,可以使用Cacheable注解将查询结果缓存起来,下一次查询同样的信息时,直接从缓存中读取,避免了频繁访问数据库,提高了响应速度;当我们需要修改用户信息时,可以使用CachePut注解将修改后的信息更新缓存,保证缓存与数据库的一致性。

    三、Redis中的击穿、穿透、雪崩的三种场景

    3.1.缓存穿透

    首先,我们来说说缓存穿透。什么是缓存穿透呢?缓存穿透问题在一定程度上与缓存命中率有关。如果我们的缓存设计的不合理,缓存的命中率非常低,那么,数据访问的绝大部分压力都会集中在后端数据库层面。

    1.什么是缓存穿透?

    如果在请求数据时,在缓存层和数据库层都没有找到符合条件的数据,也就是说,在缓存层和数据库层都没有命中数据,那么,这种情况就叫作缓存穿透。

    我们可以使用下图来表示缓存穿透的现象。

    造成缓存穿透的主要原因就是:查询某个Key对应的数据,Redis缓存中没有相应的数据,则直接到数据库中查询。数据库中也不存在要查询的数据,则数据库会返回空,而Redis也不会缓存这个空结果。这就造成每次通过这样的Key去查询数据都会直接到数据库中查询,Redis不会缓存空结果。这就造成了缓存穿透的问题。

    2.如何解决缓存穿透问题?

    既然我们知道了造成缓存穿透的主要原因就是缓存中不存在相应的数据,直接到数据库查询,数据库返回空结果,缓存中不存储空结果。

    那我们就自然而然的想到了第一种解决方案:就是把空对象缓存起来。当第一次从数据库中查询出来的结果为空时,我们就将这个空对象加载到缓存,并设置合理的过期时间,这样,就能够在一定程度上保障后端数据库的安全。

    第二种解决缓存穿透问题的解决方案:就是使用布隆过滤器,布隆过滤器可以针对大数据量的、有规律的键值进行处理。一条记录是不是存在,本质上是一个Bool值,只需要使用 1bit 就可以存储。我们可以使用布隆过滤器将这种表示是、否等操作,压缩到一个数据结构中。比如,我们最熟悉的用户性别这种数据,就非常适合使用布隆过滤器来处理。

    3.2.缓存击穿

    如果我们为缓存中的大部分数据设置了相同的过期时间,则到了某一时刻,缓存中的数据就会批量过期。

    1.什么是缓存击穿?

    如果缓存中的数据在某个时刻批量过期,导致大部分用户的请求都会直接落在数据库上,这种现象就叫作缓存击穿。

    我么可以使用下图来表示缓存击穿的线程。

    造成缓存击穿的主要原因就是:我们为缓存中的数据设置了过期时间。如果在某个时刻从数据库获取了大量的数据,并设置了相同的过期时间,这些缓存的数据就会在同一时刻失效,造成缓存击穿问题。

    2.如何解决缓存击穿问题?

    对于比较热点的数据,我们可以在缓存中设置这些数据永不过期;也可以在访问数据的时候,在缓存中更新这些数据的过期时间;如果是批量入库的缓存项,我们可以为这些缓存项分配比较合理的过期时间,避免同一时刻失效。

    还有一种解决方案就是:使用分布式锁,保证对于每个Key同时只有一个线程去查询后端的服务,某个线程在查询后端服务的同时,其他线程没有获得分布式锁的权限,需要进行等待。不过在高并发场景下,这种解决方案对于分布式锁的访问压力比较大。

    3.3.缓存雪崩

    如果缓存系统出现故障,所有的并发流量就会直接到达数据库。

    1.什么是缓存雪崩?

    如果在某一时刻缓存集中失效,或者缓存系统出现故障,所有的并发流量就会直接到达数据库。数据存储层的调用量就会暴增,用不了多长时间,数据库就会被大流量压垮,这种级联式的服务故障,就叫作缓存雪崩。

    我们可以用下图来表示缓存雪崩的现象。

    造成缓存雪崩的主要原因就是缓存集中失效,或者缓存服务发生故障,瞬间的大并发流量压垮了数据库。

    2.如何解决缓存雪崩问题?

    解决缓存雪崩问题最常用的一种方案就是保证Redis的高可用,将Redis缓存部署成高可用集群(必要时候做成异地多活),可以有效的防止缓存雪崩问题的发生。

    为了缓解大并发流量,我们也可以使用限流降级的方式防止缓存雪崩。例如,在缓存失效后,通过加锁或者使用队列来控制读数据库写缓存的线程数量。具体点就是设置某些Key只允许一个线程查询数据和写缓存,其他线程等待。则能够有效的缓解大并发流量对数据库打来的巨大冲击。

    另外,我们也可以通过数据预热的方式将可能大量访问的数据加载到缓存,在即将发生大并发访问的时候,提前手动触发加载不同的数据到缓存中,并为数据设置不同的过期时间,让缓存失效的时间点尽量均匀,不至于在同一时刻全部失效。

    请添加图片描述

    到这里我的分享就结束了,欢迎到评论区探讨交流!!

    💖如果觉得有用的话还请点个赞吧 💖

  • 相关阅读:
    TikTok美食狂潮:短视频如何塑造食物文化新趋势
    双系统ubuntu20.04(neotic版本)从0实现Gazebo仿真slam建图
    企业APP软件定制开发的关键步骤|网站小程序搭建
    发明专利转让需要多久
    OpenGL - Normal Mapping
    【C++设计模式之外观模式】分析及示例
    SQL注入:原理及示例
    【汇编】Debug的使用
    【计算机基础知识10】解析黑窗口CMD:认识CMD及常见命令
    springboot(spring)整合redis(集群)、细节、底层配置讲解
  • 原文地址:https://blog.csdn.net/weixin_74318097/article/details/134252504