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


    一、SSM整合Redis

    1.1.pom.xml配置

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

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

    pom.xml

    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. <?xml version="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. <!--1. 引入外部多文件方式 -->
    8. <bean id="propertyConfigurer"
    9. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    10. <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    11. <property name="ignoreResourceNotFound" value="true" />
    12. <property name="locations">
    13. <list>
    14. <value>classpath:jdbc.properties</value>
    15. <value>classpath:redis.properties</value>
    16. </list>
    17. </property>
    18. </bean>
    19. <!-- 随着后续学习,框架会越学越多,不能将所有的框架配置,放到同一个配制间,否者不便于管理 -->
    20. <import resource="applicationContext-mybatis.xml"></import>
    21. <import resource="spring-redis.xml"></import>
    22. <import resource="applicationContext-shiro.xml"></import>
    23. </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. }

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

    2.1.什么是Redis注解式

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

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

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

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

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

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

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

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

    2.2.为什么使用Redis注解式

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

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

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

    2.3.Redis注解式的应用

    • @Cacheable
    • @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
    • @Cacheable 作用和配置方法
    参数解释example
    value缓存的名称,在 spring 配置文件中定义,必须指定至少一个例如:
    @Cacheable(value=”mycache”)
    @Cacheable(value={”cache1”,”cache2”}
    key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合@Cacheable(value=”testcache”,key=”#userName”)
    condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存@Cacheable(value=”testcache”,condition=”#userName.length()>2”)

     

    @Cacheable (可读取与写入)
       @Cacheable是Spring框架提供的一个缓存注解,用于标记方法的返回结果可以被缓存起来,以提高系统的性能。

    如下:

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


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

    @CachePut

    • @CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
    • @CachePut 作用和配置方法
    1. @CachePut(value = "xx",key = "'cid:'+#cid")
    2. Clazz selectByPrimaryKey(Integer cid);

    参数解释example
    value缓存的名称,在 spring 配置文件中定义,必须指定至少一个@CachePut(value=”my cache”)
    key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合@CachePut(value=”testcache”,key=”#userName”)
    condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存@CachePut(value=”testcache”,condition=”#userName.length()>2”)

    @CacheEvict

    • @CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空
    • @CacheEvict 作用和配置方法
    1. @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    2. int deleteByPrimaryKey(Integer cid);
    参数解释example
    value缓存的名称,在 spring 配置文件中定义,必须指定至少一个@CacheEvict(value=”my cache”)
    key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合@CacheEvict(value=”testcache”,key=”#userName”)
    condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存@CacheEvict(value=”testcache”,condition=”#userName.length()>2”)
    allEntries是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存@CachEvict(value=”testcache”,allEntries=true)
    beforeInvocation是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存@CachEvict(value=”testcache”,beforeInvocation=true)

    SpEL上下文数据

    Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:

    名称位置描述示例
    methodNameroot对象当前被调用的方法名root.methodName
    methodroot对象当前被调用的方法root.method.name
    targetroot对象当前被调用的目标对象root.target
    targetClassroot对象当前被调用的目标对象类root.targetClass
    argsroot对象当前被调用的方法的参数列表root.args[0]
    cachesroot对象当前方法调用使用的缓存列表(如@Cacheable(value={“cache1”, “cache2”})),则有两个cacheroot.caches[0].name
    argument name执行上下文当前被调用的方法的参数,如findById(Long id),我们可以通过#id拿到参数user.id
    result执行上下文方法执行后的返回值(仅当方法执行之后的判断有效,如‘unless','cache evict'的beforeInvocation=false)result

    三. 什么是缓存雪崩、击穿、穿透?

    用户的数据一般都是存储于数据库,数据库的数据是落在磁盘上的,磁盘的读写速度可以说是计算机里最慢的硬件了。

    当用户的请求,都访问数据库的话,请求数量一上来,数据库很容易就奔溃的了,所以为了避免用户直接访问数据库,会用 Redis 作为缓存层。

    因为 Redis 是内存数据库,我们可以将数据库的数据缓存在 Redis 里,相当于数据缓存在内存,内存的读写速度比硬盘快好几个数量级,这样大大提高了系统性能。

    引入了缓存层,就会有缓存异常的三个问题,分别是缓存雪崩、缓存击穿、缓存穿透

    这三个问题也是面试中很常考察的问题,我们不光要清楚地知道它们是怎么发生,还需要知道如何解决它们。

    3.1 缓存雪崩

    通常我们为了保证缓存中的数据与数据库中的数据一致性,会给 Redis 里的数据设置过期时间,当缓存数据过期后,用户访问的数据如果不在缓存里,业务系统需要重新生成缓    存,因此就会访问数据库,并将数据更新到 Redis 里,这样后续请求都可以直接命中缓存。

    那么,当大量缓存数据在同一时间过期(失效)或者 Redis 故障宕机时,如果此时有大量的用户请求,都无法在 Redis 中处理,于是全部请求都直接访问数据库,从而导致数据库的压力骤增,严重的会造成数据库宕机,从而形成一系列连锁反应,造成整个系统崩溃,这就是缓存雪崩的问题。

    可以看到,发生缓存雪崩有两个原因:

    • 大量数据同时过期;
    • Redis 故障宕机;

    不同的诱因,应对的策略也会不同。

    举个例子

    对于系统 A,假设每天高峰期每秒 5000 个请求,本来缓存在高峰期可以扛住每秒 4000 个请求,但是缓存机器意外发生了全盘宕机。缓存挂了,此时 1 秒 5000 个请求全部落数据库,数据库必然扛不住,它会报一下警,然后就挂了。此时,如果没有采用什么特别的方案来处理这个故障,DBA 很着急,重启数据库,但是数据库立马又被新的流量给打死了。

    这就是缓存雪崩。

    大约在 3 年前,国内比较知名的一个互联网公司,曾因为缓存事故,导致雪崩,后台系统全部崩溃,事故从当天下午持续到晚上凌晨 3~4 点,公司损失了几千万。

    缓存雪崩的事前事中事后的解决方案如下。

    • 事前:redis 高可用,主从+哨兵,redis cluster,避免全盘崩溃。
    • 事中:本地 ehcache 缓存 + hystrix 限流&降级,避免 MySQL 被打死。
    • 事后:redis 持久化,一旦重启,自动从磁盘上加载数据,快速恢复缓存数据。

    用户发送一个请求,系统 A 收到请求后,先查本地 ehcache 缓存,如果没查到再查 redis。如果 ehcache 和 redis 都没有,再查数据库,将数据库中的结果,写入 ehcache 和 redis 中。

    限流组件,可以设置每秒的请求,有多少能通过组件,剩余的未通过的请求,怎么办?走降级!可以返回一些默认的值,或者友情提示,或者空白的值。

    好处:

    • 数据库绝对不会死,限流组件确保了每秒只有多少个请求能通过。
    • 只要数据库不死,就是说,对用户来说,2/5 的请求都是可以被处理的。
    • 只要有 2/5 的请求可以被处理,就意味着你的系统没死,对用户来说,可能就是点击几次刷不出来页面,但是多点几次,就可以刷出来一次。

    3.1.1大量数据同时过期

    针对大量数据同时过期而引发的缓存雪崩问题,常见的应对方法有下面这几种:

    • 均匀设置过期时间;
    • 互斥锁;
    • 后台更新缓存;

    1. 均匀设置过期时间

    如果要给缓存数据设置过期时间,应该避免将大量的数据设置成同一个过期时间。我们可以在对缓存数据设置过期时间时,给这些数据的过期时间加上一个随机数,这样就保证数据不会在同一时间过期。

    2. 互斥锁

    当业务线程在处理用户请求时,如果发现访问的数据不在 Redis 里,就加个互斥锁,保证同一时间内只有一个请求来构建缓存(从数据库读取数据,再将数据更新到 Redis 里),当缓存构建完成后,再释放锁。未能获取互斥锁的请求,要么等待锁释放后重新读取缓存,要么就返回空值或者默认值。

    实现互斥锁的时候,最好设置超时时间,不然第一个请求拿到了锁,然后这个请求发生了某种意外而一直阻塞,一直不释放锁,这时其他请求也一直拿不到锁,整个系统就会出现无响应的现象。

    3. 后台更新缓存

    业务线程不再负责更新缓存,缓存也不设置有效期,而是让缓存“永久有效”,并将更新缓存的工作交由后台线程定时更新

    事实上,缓存数据不设置有效期,并不是意味着数据一直能在内存里,因为当系统内存紧张的时候,有些缓存数据会被“淘汰”,而在缓存被“淘汰”到下一次后台定时更新缓存的这段时间内,业务线程读取缓存失败就返回空值,业务的视角就以为是数据丢失了。

    解决上面的问题的方式有两种。

    第一种方式,后台线程不仅负责定时更新缓存,而且也负责频繁地检测缓存是否有效,检测到缓存失效了,原因可能是系统紧张而被淘汰的,于是就要马上从数据库读取数据,并更新到缓存。

    这种方式的检测时间间隔不能太长,太长也导致用户获取的数据是一个空值而不是真正的数据,所以检测的间隔最好是毫秒级的,但是总归是有个间隔时间,用户体验一般。

    第二种方式,在业务线程发现缓存数据失效后(缓存数据被淘汰),通过消息队列发送一条消息通知后台线程更新缓存,后台线程收到消息后,在更新缓存前可以判断缓存是否存在,存在就不执行更新缓存操作;不存在就读取数据库数据,并将数据加载到缓存。这种方式相比第一种方式缓存的更新会更及时,用户体验也比较好。

    在业务刚上线的时候,我们最好提前把数据缓起来,而不是等待用户访问才来触发缓存构建,这就是所谓的缓存预热,后台更新缓存的机制刚好也适合干这个事情。

    3.1.2 Redis 故障宕机

    针对 Redis 故障宕机而引发的缓存雪崩问题,常见的应对方法有下面这几种:

    • 服务熔断或请求限流机制;
    • 构建 Redis 缓存高可靠集群;

    1. 服务熔断或请求限流机制

    因为 Redis 故障宕机而导致缓存雪崩问题时,我们可以启动服务熔断机制,暂停业务应用对缓存服务的访问,直接返回错误,不用再继续访问数据库,从而降低对数据库的访问压力,保证数据库系统的正常运行,然后等到 Redis 恢复正常后,再允许业务应用访问缓存服务。

    服务熔断机制是保护数据库的正常允许,但是暂停了业务应用访问缓存服系统,全部业务都无法正常工作

    为了减少对业务的影响,我们可以启用请求限流机制,只将少部分请求发送到数据库进行处理,再多的请求就在入口直接拒绝服务,等到 Redis 恢复正常并把缓存预热完后,再解除请求限流的机制。

    2. 构建 Redis 缓存高可靠集群

    服务熔断或请求限流机制是缓存雪崩发生后的应对方案,我们最好通过主从节点的方式构建 Redis 缓存高可靠集群

    如果 Redis 缓存的主节点故障宕机,从节点可以切换成为主节点,继续提供缓存服务,避免了由于 Redis 故障宕机而导致的缓存雪崩问题。


    3.2 缓存击穿

    我们的业务通常会有几个数据会被频繁地访问,比如秒杀活动,这类被频地访问的数据被称为热点数据。

    如果缓存中的某个热点数据过期了,此时大量的请求访问了该热点数据,就无法从缓存中读取,直接访问数据库,数据库很容易就被高并发的请求冲垮,这就是缓存击穿的问题。

    可以发现缓存击穿跟缓存雪崩很相似,你可以认为缓存击穿是缓存雪崩的一个子集。

    应对缓存击穿可以采取前面说到两种方案:

    • 互斥锁方案,保证同一时间只有一个业务线程更新缓存,未能获取互斥锁的请求,要么等待锁释放后重新读取缓存,要么就返回空值或者默认值。
    • 不给热点数据设置过期时间,由后台异步更新缓存,或者在热点数据准备要过期前,提前通知后台线程更新缓存以及重新设置过期时间;

    3.3 缓存穿透

    当发生缓存雪崩或击穿时,数据库中还是保存了应用要访问的数据,一旦缓存恢复相对应的数据,就可以减轻数据库的压力,而缓存穿透就不一样了。

    当用户访问的数据,既不在缓存中,也不在数据库中,导致请求在访问缓存时,发现缓存缺失,再去访问数据库时,发现数据库中也没有要访问的数据,没办法构建缓存数据,来服务后续的请求。那么当有大量这样的请求到来时,数据库的压力骤增,这就是缓存穿透的问题。

    缓存穿透的发生一般有这两种情况:

    • 业务误操作,缓存中的数据和数据库中的数据都被误删除了,所以导致缓存和数据库中都没有数据;
    • 黑客恶意攻击,故意大量访问某些读取不存在数据的业务;

    举个例子

    对于系统A,假设一秒 5000 个请求,结果其中 4000 个请求是黑客发出的恶意攻击。

    黑客发出的那 4000 个攻击,缓存中查不到,每次你去数据库里查,也查不到。

    举个栗子。数据库 id 是从 1 开始的,结果黑客发过来的请求 id 全部都是负数。这样的话,缓存中不会有,请求每次都“视缓存于无物”,直接查询数据库。这种恶意攻击场景的缓存穿透就会直接把数据库给打死。

    解决方式很简单,每次系统 A 从数据库中只要没查到,就写一个空值到缓存里去,比如 set -999 UNKNOWN。然后设置一个过期时间,这样的话,下次有相同的 key 来访问的时候,在缓存失效之前,都可以直接从缓存中取数据。

    应对缓存穿透的方案,常见的方案有三种。

    • 第一种方案,非法请求的限制;
    • 第二种方案,缓存空值或者默认值;
    • 第三种方案,使用布隆过滤器快速判断数据是否存在,避免通过查询数据库来判断数据是否存在;

    第一种方案,非法请求的限制

    当有大量恶意请求访问不存在的数据的时候,也会发生缓存穿透,因此在 API 入口处我们要判断求请求参数是否合理,请求参数是否含有非法值、请求字段是否存在,如果判断出是恶意请求就直接返回错误,避免进一步访问缓存和数据库。

    第二种方案,缓存空值或者默认值

    当我们线上业务发现缓存穿透的现象时,可以针对查询的数据,在缓存中设置一个空值或者默认值,这样后续请求就可以从缓存中读取到空值或者默认值,返回给应用,而不会继续查询数据库。

    第三种方案,使用布隆过滤器快速判断数据是否存在,避免通过查询数据库来判断数据是否存在。

    我们可以在写入数据库数据时,使用布隆过滤器做个标记,然后在用户请求到来时,业务线程确认缓存失效后,可以通过查询布隆过滤器快速判断数据是否存在,如果不存在,就不用通过查询数据库来判断数据是否存在。

    即使发生了缓存穿透,大量请求只会查询 Redis 和布隆过滤器,而不会查询数据库,保证了数据库能正常运行,Redis 自身也是支持布隆过滤器的。

    那问题来了,布隆过滤器是如何工作的呢?接下来,我介绍下。

    布隆过滤器由「初始值都为 0 的位图数组」和「 N 个哈希函数」两部分组成。当我们在写入数据库数据时,在布隆过滤器里做个标记,这样下次查询数据是否在数据库时,只需要查询布隆过滤器,如果查询到数据没有被标记,说明不在数据库中。

    布隆过滤器会通过 3 个操作完成标记:

    • 第一步,使用 N 个哈希函数分别对数据做哈希计算,得到 N 个哈希值;
    • 第二步,将第一步得到的 N 个哈希值对位图数组的长度取模,得到每个哈希值在位图数组的对应位置。
    • 第三步,将每个哈希值在位图数组的对应位置的值设置为 1;

    举个例子,假设有一个位图数组长度为 8,哈希函数 3 个的布隆过滤器。

    在数据库写入数据 x 后,把数据 x 标记在布隆过滤器时,数据 x 会被 3 个哈希函数分别计算出 3 个哈希值,然后在对这 3 个哈希值对 8 取模,假设取模的结果为 1、4、6,然后把位图数组的第 1、4、6 位置的值设置为 1。当应用要查询数据 x 是否数据库时,通过布隆过滤器只要查到位图数组的第 1、4、6 位置的值是否全为 1,只要有一个为 0,就认为数据 x 不在数据库中

    布隆过滤器由于是基于哈希函数实现查找的,高效查找的同时存在哈希冲突的可能性,比如数据 x 和数据 y 可能都落在第 1、4、6 位置,而事实上,可能数据库中并不存在数据 y,存在误判的情况。

    所以,查询布隆过滤器说数据存在,并不一定证明数据库中存在这个数据,但是查询到数据不存在,数据库中一定就不存在这个数据


    总结

    缓存异常会面临的三个问题:缓存雪崩、击穿和穿透。

    其中,缓存雪崩和缓存击穿主要原因是数据不在缓存中,而导致大量请求访问了数据库,数据库压力骤增,容易引发一系列连锁反应,导致系统奔溃。不过,一旦数据被重新加载回缓存,应用又可以从缓存快速读取数据,不再继续访问数据库,数据库的压力也会瞬间降下来。因此,缓存雪崩和缓存击穿应对的方案比较类似。

    而缓存穿透主要原因是数据既不在缓存也不在数据库中。因此,缓存穿透与缓存雪崩、击穿应对的方案不太一样。

    我这里整理了表格,你可以从下面这张表格很好的知道缓存雪崩、击穿和穿透的区别以及应对方案。

  • 相关阅读:
    CloudCompare 二次开发(9)——半径滤波
    我的MySQL为什么版本不一?
    Shell 流程控制
    【论文阅读】多模态模型CoCa
    热门项目披露:湖南民航置业有限公司70%股权转让
    python入门篇03 基础案例 python版与java版 语法不同之处
    Qt各种指针的使用总结
    Hawkeye
    小米笔试真题一
    云原生 | kubernetes - Deployment
  • 原文地址:https://blog.csdn.net/liaozhixiangjava/article/details/134250469