• SSM之Spring注解式缓存Redis


                                                                         目录

    一、Spring整合Redis

    ①导入相关的pom依赖

    ②添加对应的配置文件

    ③Spring-redis的整合配置文件

    ④测试

    完整版pom依赖

    二、reids的注解式开发

     ① @Cacheable

    ② @CachePut 

    ③ @CacheEvict 

    小结

     三、redis的击穿、穿透、雪崩现象及解决方案 👀👀

    击穿:高并发量的同时key失效,导致请求直接到达数据库

    穿透: 很多请求都在访问数据库一定不存在的数据,造成请求将缓存和数据库都穿透的情况

    雪崩: 雪崩和击穿类似,不同的是击穿是一个热点 Key 某时刻失效,而雪崩是大量的热点 Key 在一瞬间失效 

    简略图解

    小结


    一、Spring整合Redis

    ①导入相关的pom依赖

    1. <redis.version>2.9.0redis.version>
    2. <redis.spring.version>1.7.1.RELEASEredis.spring.version>
    3. <dependency>
    4. <groupId>redis.clientsgroupId>
    5. <artifactId>jedisartifactId>
    6. <version>${redis.version}version>
    7. dependency>
    8. <dependency>
    9. <groupId>org.springframework.datagroupId>
    10. <artifactId>spring-data-redisartifactId>
    11. <version>${redis.spring.version}version>
    12. dependency>

    ②添加对应的配置文件

    redis.properties

    1. redis.hostName=192.168.141.128
    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

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

    ③Spring-redis的整合配置文件

    注意1:jdbc.properties与redis.properties文件在整合的时候会有冲突现象,解决方式,用引入外部多文件方式进行处理

    注意2:pom中可以编译的文件以及目录

    记得下载插件lombox

    1. package com.zking.ssm.redis;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.cache.annotation.Cacheable;
    4. import org.springframework.cache.interceptor.KeyGenerator;
    5. import org.springframework.util.ClassUtils;
    6. import java.lang.reflect.Array;
    7. import java.lang.reflect.Method;
    8. /**
    9. * 指定redis中的key value存储中的key字符串的生成规则
    10. * uname:zs 以前这个uname是手动赋予的
    11. * 这个uname不想手写了,就通过它来写
    12. *
    13. * @enableCache 这个key就通过它来做的
    14. */
    15. @Slf4j
    16. public class CacheKeyGenerator implements KeyGenerator {
    17. // custom cache key
    18. public static final int NO_PARAM_KEY = 0;
    19. public static final int NULL_PARAM_KEY = 53;
    20. @Cacheable
    21. @Override
    22. public Object generate(Object target, Method method, Object... params) {
    23. StringBuilder key = new StringBuilder();
    24. // com.zking.service.ClzServie.get:1
    25. key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");
    26. if (params.length == 0) {
    27. key.append(NO_PARAM_KEY);
    28. } else {
    29. int count = 0;
    30. for (Object param : params) {
    31. if (0 != count) {//参数之间用,进行分隔
    32. key.append(',');
    33. }
    34. if (param == null) {
    35. key.append(NULL_PARAM_KEY);
    36. } else if (ClassUtils.isPrimitiveArray(param.getClass())) {
    37. int length = Array.getLength(param);
    38. for (int i = 0; i < length; i++) {
    39. key.append(Array.get(param, i));
    40. key.append(',');
    41. }
    42. } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
    43. key.append(param);
    44. } else {//Java一定要重写hashCode和eqauls
    45. key.append(param.hashCode());
    46. }
    47. count++;
    48. }
    49. }
    50. String finalKey = key.toString();
    51. // IEDA要安装lombok插件
    52. log.debug("using cache key={}", finalKey);
    53. return finalKey;
    54. }
    55. }

    这个时候运行会出错,因为redis.properties与jdbc.properties在与Spring做整合时发生冲突;所以引入配置文件的地方要放到中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="applicationContext-redis.xml">import>
    20. <import resource="applicationContext-shiro.xml"/>
    21. beans>

     

     

    ④测试

     

     

     完整版pom依赖

    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. <redis.version>2.9.0redis.version>
    28. <redis.spring.version>1.7.1.RELEASEredis.spring.version>
    29. properties>
    30. <dependencies>
    31. <dependency>
    32. <groupId>org.springframeworkgroupId>
    33. <artifactId>spring-contextartifactId>
    34. <version>${spring.version}version>
    35. dependency>
    36. <dependency>
    37. <groupId>org.springframeworkgroupId>
    38. <artifactId>spring-ormartifactId>
    39. <version>${spring.version}version>
    40. dependency>
    41. <dependency>
    42. <groupId>org.springframeworkgroupId>
    43. <artifactId>spring-txartifactId>
    44. <version>${spring.version}version>
    45. dependency>
    46. <dependency>
    47. <groupId>org.springframeworkgroupId>
    48. <artifactId>spring-aspectsartifactId>
    49. <version>${spring.version}version>
    50. dependency>
    51. <dependency>
    52. <groupId>org.springframeworkgroupId>
    53. <artifactId>spring-webartifactId>
    54. <version>${spring.version}version>
    55. dependency>
    56. <dependency>
    57. <groupId>org.springframeworkgroupId>
    58. <artifactId>spring-testartifactId>
    59. <version>${spring.version}version>
    60. dependency>
    61. <dependency>
    62. <groupId>org.mybatisgroupId>
    63. <artifactId>mybatisartifactId>
    64. <version>${mybatis.version}version>
    65. dependency>
    66. <dependency>
    67. <groupId>mysqlgroupId>
    68. <artifactId>mysql-connector-javaartifactId>
    69. <version>${mysql.version}version>
    70. dependency>
    71. <dependency>
    72. <groupId>com.github.pagehelpergroupId>
    73. <artifactId>pagehelperartifactId>
    74. <version>${pagehelper.version}version>
    75. dependency>
    76. <dependency>
    77. <groupId>org.mybatisgroupId>
    78. <artifactId>mybatis-springartifactId>
    79. <version>${mybatis.spring.version}version>
    80. dependency>
    81. <dependency>
    82. <groupId>org.apache.commonsgroupId>
    83. <artifactId>commons-dbcp2artifactId>
    84. <version>${commons.dbcp2.version}version>
    85. dependency>
    86. <dependency>
    87. <groupId>org.apache.commonsgroupId>
    88. <artifactId>commons-pool2artifactId>
    89. <version>${commons.pool2.version}version>
    90. dependency>
    91. <dependency>
    92. <groupId>org.apache.logging.log4jgroupId>
    93. <artifactId>log4j-coreartifactId>
    94. <version>${log4j2.version}version>
    95. dependency>
    96. <dependency>
    97. <groupId>org.apache.logging.log4jgroupId>
    98. <artifactId>log4j-apiartifactId>
    99. <version>${log4j2.version}version>
    100. dependency>
    101. <dependency>
    102. <groupId>org.apache.logging.log4jgroupId>
    103. <artifactId>log4j-webartifactId>
    104. <version>${log4j2.version}version>
    105. dependency>
    106. <dependency>
    107. <groupId>junitgroupId>
    108. <artifactId>junitartifactId>
    109. <version>${junit.version}version>
    110. <scope>testscope>
    111. dependency>
    112. <dependency>
    113. <groupId>javax.servletgroupId>
    114. <artifactId>javax.servlet-apiartifactId>
    115. <version>${servlet.version}version>
    116. <scope>providedscope>
    117. dependency>
    118. <dependency>
    119. <groupId>org.projectlombokgroupId>
    120. <artifactId>lombokartifactId>
    121. <version>${lombok.version}version>
    122. <scope>providedscope>
    123. dependency>
    124. <dependency>
    125. <groupId>org.springframeworkgroupId>
    126. <artifactId>spring-webmvcartifactId>
    127. <version>${spring.version}version>
    128. dependency>
    129. <dependency>
    130. <groupId>javax.servlet.jspgroupId>
    131. <artifactId>javax.servlet.jsp-apiartifactId>
    132. <version>2.3.3version>
    133. dependency>
    134. <dependency>
    135. <groupId>jstlgroupId>
    136. <artifactId>jstlartifactId>
    137. <version>1.2version>
    138. dependency>
    139. <dependency>
    140. <groupId>taglibsgroupId>
    141. <artifactId>standardartifactId>
    142. <version>1.1.2version>
    143. dependency>
    144. <dependency>
    145. <groupId>commons-fileuploadgroupId>
    146. <artifactId>commons-fileuploadartifactId>
    147. <version>1.3.3version>
    148. dependency>
    149. <dependency>
    150. <groupId>org.hibernategroupId>
    151. <artifactId>hibernate-validatorartifactId>
    152. <version>6.0.7.Finalversion>
    153. dependency>
    154. <dependency>
    155. <groupId>com.fasterxml.jackson.coregroupId>
    156. <artifactId>jackson-databindartifactId>
    157. <version>2.9.3version>
    158. dependency>
    159. <dependency>
    160. <groupId>com.fasterxml.jackson.coregroupId>
    161. <artifactId>jackson-coreartifactId>
    162. <version>2.9.3version>
    163. dependency>
    164. <dependency>
    165. <groupId>com.fasterxml.jackson.coregroupId>
    166. <artifactId>jackson-annotationsartifactId>
    167. <version>2.9.3version>
    168. dependency>
    169. <dependency>
    170. <groupId>redis.clientsgroupId>
    171. <artifactId>jedisartifactId>
    172. <version>${redis.version}version>
    173. dependency>
    174. <dependency>
    175. <groupId>org.springframework.datagroupId>
    176. <artifactId>spring-data-redisartifactId>
    177. <version>${redis.spring.version}version>
    178. dependency>
    179. dependencies>
    180. <build>
    181. <finalName>ssm2finalName>
    182. <resources>
    183. <resource>
    184. <directory>src/main/javadirectory>
    185. <includes>
    186. <include>**/*.xmlinclude>
    187. includes>
    188. resource>
    189. <resource>
    190. <directory>src/main/resourcesdirectory>
    191. <includes>
    192. <include>*.propertiesinclude>
    193. <include>*.xmlinclude>
    194. includes>
    195. resource>
    196. resources>
    197. <pluginManagement>
    198. <plugins>
    199. <plugin>
    200. <groupId>org.apache.maven.pluginsgroupId>
    201. <artifactId>maven-compiler-pluginartifactId>
    202. <version>${maven.compiler.plugin.version}version>
    203. <configuration>
    204. <source>${maven.compiler.source}source>
    205. <target>${maven.compiler.target}target>
    206. <encoding>${project.build.sourceEncoding}encoding>
    207. configuration>
    208. plugin>
    209. <plugin>
    210. <groupId>org.mybatis.generatorgroupId>
    211. <artifactId>mybatis-generator-maven-pluginartifactId>
    212. <version>1.3.2version>
    213. <dependencies>
    214. <dependency>
    215. <groupId>mysqlgroupId>
    216. <artifactId>mysql-connector-javaartifactId>
    217. <version>${mysql.version}version>
    218. dependency>
    219. dependencies>
    220. <configuration>
    221. <overwrite>trueoverwrite>
    222. configuration>
    223. plugin>
    224. <plugin>
    225. <artifactId>maven-clean-pluginartifactId>
    226. <version>3.1.0version>
    227. plugin>
    228. <plugin>
    229. <artifactId>maven-resources-pluginartifactId>
    230. <version>3.0.2version>
    231. plugin>
    232. <plugin>
    233. <artifactId>maven-compiler-pluginartifactId>
    234. <version>3.8.0version>
    235. plugin>
    236. <plugin>
    237. <artifactId>maven-surefire-pluginartifactId>
    238. <version>2.22.1version>
    239. plugin>
    240. <plugin>
    241. <artifactId>maven-war-pluginartifactId>
    242. <version>3.2.2version>
    243. plugin>
    244. <plugin>
    245. <artifactId>maven-install-pluginartifactId>
    246. <version>2.5.2version>
    247. plugin>
    248. <plugin>
    249. <artifactId>maven-deploy-pluginartifactId>
    250. <version>2.8.2version>
    251. plugin>
    252. plugins>
    253. pluginManagement>
    254. build>
    255. project>

    二、reids的注解式开发

    启动虚拟机VMware,启动虚拟机连接工具

    连接redis服务6379

     ① @Cacheable

    配置在方法或类上

    作用:本方法执行后,先去缓存看有没有数据,如果没有,从数据库中查找出来,给缓存中存一份,返回结果, 下次本方法执行,在缓存未过期情况下,先在缓存中查找,有的话直接返回,没有的话从数据库查找

     ClazzBiz

    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.Cacheable;
    5. import java.util.List;
    6. import java.util.Map;
    7. public interface ClazzBiz {
    8. int deleteByPrimaryKey(Integer cid);
    9. int insert(Clazz record);
    10. int insertSelective(Clazz record);
    11. Clazz selectByPrimaryKey(Integer cid);
    12. int updateByPrimaryKeySelective(Clazz record);
    13. int updateByPrimaryKey(Clazz record);
    14. List listPager(Clazz clazz, PageBean pageBean);
    15. List listMapPager(Clazz clazz, PageBean pageBean);
    16. }

    读Spring上下文  

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"classpath:applicationContext.xml"})

    ClazzBizTest 

    1. package com.zking.ssm.redis;
    2. import com.zking.ssm.biz.ClazzBiz;
    3. import org.junit.Test;
    4. import org.junit.runner.RunWith;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.test.context.ContextConfiguration;
    7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    8. /**
    9. * @author 小坤
    10. * @create 2022-10-28 17:00
    11. */
    12. @RunWith(SpringJUnit4ClassRunner.class)
    13. @ContextConfiguration(locations={"classpath:applicationContext.xml"})
    14. public class ClazzBizTest {
    15. @Autowired
    16. private ClazzBiz clazzBiz;
    17. @Test
    18. public void test1(){
    19. System.out.println(clazzBiz.selectByPrimaryKey(1));
    20. System.out.println(clazzBiz.selectByPrimaryKey(1));
    21. }
    22. }

    运行图 

    修改ClazzBiz里的注释

    1. @Cacheable(value = "xx")
    2. Clazz selectByPrimaryKey(Integer cid);

    现在我们看看redis的桌面管理器中显示

     

    再次修改注释中的属性 key改变原有的key生成规则

    1. // xx=cache-cid:1
    2. // key的作用是改变原有的key生成规则
    3. @Cacheable(value = "xx",key = "'cid:'+#cid")
    4. Clazz selectByPrimaryKey(Integer cid);
    1. @Test
    2. public void test1(){
    3. System.out.println(clazzBiz.selectByPrimaryKey(2));
    4. System.out.println(clazzBiz.selectByPrimaryKey(2));
    5. }

    redis最终存储的对象是JSON 

    修改注释里的属性 condition判断什么时候修改key属性 将库清空 

                                                                                                           

    1. // xx=cache-cid:1
    2. // key的作用是改变原有的key生成规则
    3. // 改变它的生成规则,只有key大于6的时候生成缓存,key小于6不生成缓存
    4. @Cacheable(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
    5. Clazz selectByPrimaryKey(Integer cid);
    1. @Test
    2. public void test1(){
    3. System.out.println(clazzBiz.selectByPrimaryKey(3));
    4. System.out.println(clazzBiz.selectByPrimaryKey(3));
    5. }

    运行图

    查询了两次数据库  

     修改ClazzBizTest

    1. @Test
    2. public void test1(){
    3. System.out.println(clazzBiz.selectByPrimaryKey(8));
    4. System.out.println(clazzBiz.selectByPrimaryKey(8));
    5. }

    运行结果肯定查询了一次数据库,还生成了缓存👀👀

     

    ② @CachePut 

    类似于更新操作,即每次不管缓存中有没有结果,都从数据库查找结果,并将结果更新到缓存,并返回结果。

    ClazzBiz

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

    ClazzBizTest

    1. @Test
    2. public void test1(){
    3. System.out.println(clazzBiz.selectByPrimaryKey(9));
    4. System.out.println(clazzBiz.selectByPrimaryKey(9));
    5. }

     运行图

    ③ @CacheEvict 

    用来清除用在本方法或者类上的缓存数据(把指定的数据清空的同时,清除掉redis桌面管理器这里面的缓存清空某一条数据,你传的id是什么,就把id对应的缓存给清掉)

    ClazzBiz

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

    ClazzBizTest

    1. @Test
    2. public void test2(){
    3. clazzBiz.deleteByPrimaryKey(9);
    4. }

    ClazzBizImpl

    1. @Override
    2. public int deleteByPrimaryKey(Integer cid) {
    3. // return clazzMapper.deleteByPrimaryKey(cid);
    4. System.out.println("不做任何操作,因为我们只清除缓存,不清除数据库");
    5. return 0;
    6. }

     ClazzBizTest

    1. @Test
    2. public void test2(){
    3. clazzBiz.deleteByPrimaryKey(10);
    4. }

    小结:

    ① @Cacheable 使用注解,缓存并使用

    ② @CaChePut 只放缓存,不查缓存

    ③ @CacheEvict 清除缓存,可以去设置权限,清除指定缓存、清除所有缓存

     三、redis的击穿、穿透、雪崩现象及解决方案 👀👀

    击穿:高并发量的同时key失效,导致请求直接到达数据库

    设置锁
    1.获取 Redis 锁,如果没有获取到,则回到任务队列继续排队
    2.获取到锁,从数据库拉取数据并放入缓存中
    3.释放锁,其他请求从缓存中拿到数据

    限流:请求redis之前做流量削峰

    穿透: 很多请求都在访问数据库一定不存在的数据,造成请求将缓存和数据库都穿透的情况

    规则排除
    可以增加一些参数检验。例如数据库数据 id 一般都是递增的,如果请求 id = -10 这种参数,势必绕过Redis。避免这种情况,可以对用户真实性检验等操作。

    null值填充
    当缓存穿透时,redis存入一个类似null的值,下次访问则直接缓存返回空,当数据库中存在该数据的值则需要把redis存在的null值清除并载入新值,此方案不能解决频繁随机不规则的key请求。

    雪崩: 雪崩和击穿类似,不同的是击穿是一个热点 Key 某时刻失效,而雪崩是大量的热点 Key 在一瞬间失效 

    给不同的热点key设置不同的缓存策略

    简略图解

    击穿、穿透、雪崩它们都有共同点会有大量请求:通用的解决方案限流,限流用到的技术RabbitMQ,流量雪崩
    击穿的解决方案:给redis上锁,第一个请求拿到锁,从数据库拿数据,缓存到redis中,

                                然后在把锁释放,后面的请求就可以访问了
     

    穿透:因为它的现象是反而不存在的数据,redis跟MySQL都没有这条数据但此时我们可以在

              redis设置一条压根就不存在的数据,那下次在访问的话,

               那么redis就有数据请求就不会到达MySQL,这是关于穿透

    雪崩:是因为大量的key同一时间发生变化,那我们可以采用disregard的方式,
                  给不同的key设置不同的缓存策略,设置不同的存活时间

    小结:

    reids的击穿穿透雪崩 
    击穿:一瞬间大量请求访问某一个key的数据,而这个key正好失效;那么此时大量请求会到数据库

    方案:限流,设置redis锁 

    穿透:访问一个redis以及数据库压根不存在的数据,每一次请求都会到达数据库

    方案:设置“null”值

    雪崩:一瞬间大量请求访问多个key的数据,而多个key同时失效

    方案:通过定时任务,设置不同的缓存机制
     

                                                                                                                                                               

  • 相关阅读:
    android 固定进度环形刷新效果
    【记录】GLICB2.25 升级时报错
    春秋云境CVE-2018-20604
    ElasticSearch映射与模板介绍
    Word插入希腊字母及特殊符号 分类整
    idea常用快捷键持续更新
    C++精简实现2048游戏逻辑
    微服务架构陷阱与挑战
    安装cuda和cudnn之后torch.cuda_is_available()为False
    Makefile与CMakeLists.txt
  • 原文地址:https://blog.csdn.net/weixin_67450855/article/details/127577380