• Redis-----SSM整合redis及redis的注解式开发以及redis的击穿,穿透,雪崩三种解决方案


    目录

    SSM项目整合Redis

    导入pom依赖

    配置文件spring-redis.xml

     redis.properties

    配置redis的key生成策略

    redis的注解式开发及应用场景

    什么是redis的注解式

    redis注解式的场景应用

     @Cacheable

    自定义策略

    @Cacheable可以指定三个属性,value、key和condition。

    ​编辑 CachePut 注解

    redis的击穿 穿透 雪崩 

    击穿

     穿透

    雪崩


    SSM项目整合Redis

     redis是nosql数据库,mysql是sql数据库,都是数据库因此可以参考mysql整合ssm项目的过程。

    导入pom依赖

    以下是在pom.xml文件中添加redis的依赖

    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>

    配置文件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>

     redis.properties

    创建 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

    配置redis的key生成策略

    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. }

    redis的注解式开发及应用场景

    什么是redis的注解式

    Redis并不支持注解式。注解式是一种常见的编程范式,常见于一些基于Java的框架,如Spring。它允许开发者通过在代码中使用注解来声明一些元数据,以简化配置和提供额外的功能。

    然而,在Redis中,我们通常使用客户端库(如Jedis或Lettuce)与Redis进行交互。这些客户端库提供了一组丰富的API来与Redis进行通信,但它们并不支持直接使用注解来实现功能。

    当使用Redis时,通常需要手动编写代码来执行各种操作,如存储、检索、更新和删除数据。这些操作通常通过调用客户端库提供的方法来完成,而不是使用注解。

    redis注解式的场景应用

     @Cacheable

    @Cacheable是Spring框架提供的一个缓存注解,用于标记方法的返回结果可以被缓存起来,以提高系统的性能。@Cacheable注解的作用如下

    1. 缓存结果:当一个被@Cacheable注解修饰的方法被调用时,Spring会先检查缓存中是否存在该方法的返回结果。如果缓存中已经存在,则直接返回缓存中的结果,而不再执行方法体内的代码逻辑。

    2. 缓存键生成:@Cacheable注解可以指定一个缓存键(key)来标识缓存中的数据。默认情况下,缓存键是由方法的参数组成的。如果两次调用的方法参数相同,则会使用相同的缓存键,从而直接返回缓存中的结果。

    3. 缓存管理:@Cacheable注解可以与其他缓存管理工具(如Redis、Ehcache等)进行整合使用。通过在配置文件中配置相应的缓存管理器,可以将方法的返回结果存储到指定的缓存中,以供后续的调用使用。

    4. 缓存失效:@Cacheable注解还可以指定一个失效时间(TTL)来控制缓存的有效期。当缓存的有效期过期后,下一次调用该方法时会重新执行方法体内的代码逻辑,并将新的结果存储到缓存中。

    定义查询接口使用Cacheable注解

     

    编写测试类  

     测试结果:

    自定义策略

    @Cacheable可以指定三个属性,value、key和condition。

     CachePut 注解

    它的使用与Cacheable的使用一致,它们的区别

    Cacheable:会在redis中存储数据,同时也会读取数据

    CachePut:只会在redis储存数据,不会进行读取操作

     

    测试类 

     

    redis的击穿 穿透 雪崩 

    缓存中常见的三种现象:击穿、穿透、雪崩。 

    击穿

    当缓存中不存在某个key的数据,而有大量并发请求访问这个key时,这些请求会直接穿过缓存,去访问数据库,导致数据库压力过大,甚至宕机。这种现象称为“击穿”。

    解决方法:

    使用互斥锁或分布式锁,保证只有一个线程去访问数据库,其他线程等待结果即可。 

     穿透

    当某个key对应的数据在缓存中不存在,而且这个key被大量请求访问时,这些请求会直接访问数据库,导致数据库压力过大,甚至宕机。这种现象称为“穿透”。 

    解决方法:

    在缓存中预先设置这个key对应的空值或默认值,避免大量请求直接访问数据库。 

    雪崩

    当缓存中的大量数据同时失效,而且这些数据被大量请求访问时,这些请求会直接访问数据库,导致数据库压力过大,甚至宕机。这种现象称为“雪崩”。 

    解决方法:

    • - 缓存数据的失效时间设置随机,避免大量数据同时失效。
    • - 使用多级缓存架构,避免单点故障。
    • - 使用熔断机制,当缓存失效时,暂时屏蔽对数据库的访问,避免压力过大。

    okok,今天就到这里了,下班!下班!!!!!!!!!!!! 

  • 相关阅读:
    Vite4TSX前端版本号生成
    【Spring Cloud】新闻头条微服务项目:分布式文件系统MinIO实现文章页面存取
    基于vue和nodejs毕业设计酒店预约管理系统
    【面试经典150 | 哈希表】快乐数
    二叉树前中后序遍历【非递归】
    Azure Data Factory(八)数据集验证之服务主体(Service Principal)
    CloudCompare 技巧四 点云匹配
    使用文本编辑器解决Word文档加密后忘记密码问题
    要被抖音笑死了,打开个网页就算黑客?
    ubuntu升级python到python3.11(可能是全网最靠谱的方法,亲测有效)
  • 原文地址:https://blog.csdn.net/m0_74934282/article/details/134261760