• Redis之与SSM集成Spring注解式缓存


    目录

    一.整合

    1.1.整合应用

    1.1.1.pom配置

    1.1.2.所需配置

    二.注解式开发及应用场景

    2.1. @Cacheable

    2.2. @CachePut 

    2.3. @CacheEvict

    2.4.总结

    三.redis的击穿穿透雪崩

                    好啦今天就到这里了哦!!希望能帮到你哦!! 


    一.整合

    1.1.整合应用

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

    1.1.2.所需配置

    在SSM项目中创建一个 spring-readis.xml,配置Redis连接信息,配置数据源,配置序列化器及redis的key生成策略,配置RedisTemplate。

    创建 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 配置文件,在其中配置以下

    redis连接池的配置

    1. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    2. <property name="maxIdle" value="${redis.maxIdle}"/>
    3. <property name="maxTotal" value="${redis.maxTotal}"/>
    4. <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
    5. <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
    6. <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
    7. <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
    8. <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    9. <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
    10. bean>

    配置redis连接工厂

    1. <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
    2. destroy-method="destroy">
    3. <property name="poolConfig" ref="poolConfig"/>
    4. <property name="hostName" value="${redis.hostName}"/>
    5. <property name="port" value="${redis.port}"/>
    6. <property name="password" value="${redis.password}"/>
    7. <property name="timeout" value="${redis.timeout}"/>
    8. bean>

    redis操作模板

    1. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    2. <property name="connectionFactory" ref="connectionFactory"/>
    3. <property name="keySerializer">
    4. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    5. property>
    6. <property name="valueSerializer">
    7. <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    8. property>
    9. <property name="hashKeySerializer">
    10. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    11. property>
    12. <property name="hashValueSerializer">
    13. <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    14. property>
    15. <property name="enableTransactionSupport" value="true"/>
    16. bean>

    配置缓存管理器

    1. <!-- 5.配置缓存管理器 -->
    2. <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
    3. <constructor-arg name="redisOperations" ref="redisTemplate"/>
    4. <!--redis缓存数据过期时间单位秒-->
    5. <property name="defaultExpiration" value="${redis.expiration}"/>
    6. <!--是否使用缓存前缀,与cachePrefix相关-->
    7. <property name="usePrefix" value="true"/>
    8. <!--配置缓存前缀名称-->
    9. <property name="cachePrefix">
    10. <bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix">
    11. <constructor-arg index="0" value="-cache-"/>
    12. </bean>
    13. </property>
    14. </bean>

    创建 CacheKeyGenerator.java 配置缓存生成键名的生成规则

    1. package com.junlinyi.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. }

     最后 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.junlinyi.ssm.redis.CacheKeyGenerator">bean>
    57. <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
    58. beans>

     创建 applicationContext-shiro.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. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="shiroRealm" class="com.junlinyi.ssm.shiro.MyRealm">
    6. <property name="userBiz" ref="userBiz" />
    7. <property name="credentialsMatcher">
    8. <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    9. <property name="hashAlgorithmName" value="md5"/>
    10. <property name="hashIterations" value="1024"/>
    11. <property name="storedCredentialsHexEncoded" value="true"/>
    12. bean>
    13. property>
    14. bean>
    15. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    16. <property name="sessionManager" ref="sessionManager">property>
    17. <property name="realm" ref="shiroRealm" />
    18. bean>
    19. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    20. <property name="securityManager" ref="securityManager" />
    21. <property name="loginUrl" value="/login"/>
    22. <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
    23. <property name="filterChainDefinitions">
    24. <value>
    25. /user/login=anon
    26. /user/updatePwd.jsp=authc
    27. /admin/*.jsp=roles[4]
    28. /user/teacher.jsp=perms[2]
    29. value>
    30. property>
    31. bean>
    32. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    33. <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator">
    34. bean>
    35. <bean id="customSessionDao" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO">
    36. <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    37. bean>
    38. <bean id="shiroSessionListener" class="com.junlinyi.ssm.shiro.MySessionListener"/>
    39. <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
    40. <constructor-arg value="shiro.session"/>
    41. <property name="maxAge" value="-1"/>
    42. <property name="httpOnly" value="true"/>
    43. bean>
    44. <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    45. <property name="globalSessionTimeout" value="120000"/>
    46. <property name="sessionDAO" ref="customSessionDao"/>
    47. <property name="sessionValidationInterval" value="60000"/>
    48. <property name="deleteInvalidSessions" value="true"/>
    49. <property name="sessionListeners">
    50. <list>
    51. <ref bean="shiroSessionListener"/>
    52. list>
    53. property>
    54. <property name="sessionIdCookie" ref="sessionIdCookie"/>
    55. <property name="sessionIdUrlRewritingEnabled" value="true"/>
    56. bean>
    57. beans>

     在引用的配置文件中引用以上配置的文件 如 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>

     以上是基本的配置步骤,根据具体的项目需求和框架版本可能会有所不同。在实际应用中,还可以根据需要配置Redis的集群、哨兵模式、持久化等功能,以提高系统的可用性和可靠性。

    二.注解式开发及应用场景

    2.1. @Cacheable

    @Cacheable是Spring Framework中的一个注解,用于声明方法的返回值是可以被缓存的。这意味着方法的返回值将被缓存在内存中,以便之后的调用可以直接返回缓存的结果,而无需再次执行该方法。

    具体来说,@Cacheable注解的作用如下:

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

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

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

    4. 缓存失效:@Cacheable注解还可以指定一个失效时间(TTL)来控制缓存的有效期。当缓存的有效期过期后,下一次调用该方法时会重新执行方法体内的代码逻辑,并将新的结果存储到缓存中。
    使用@Cacheable注解可以有效地减少对数据库或其他资源的访问次数,提高系统的响应速度和并发处理能力。但需要注意的是,使用缓存时需要权衡缓存的一致性和实时性,避免数据不一致或过期的问题。

    常用属性及用法作用

    @Cacheable注解有以下常用属性及用法作用:

     

    value:指定缓存的名称,用于区分不同的缓存空间。可以在配置文件中配置相应的缓存管理器,以决定将缓存存储在哪个缓存空间中。可以指定多个缓存名称,使用逗号分隔。

    key:指定缓存的键,用于标识缓存中的数据。默认情况下,缓存键是由方法的参数组成的。可以使用SpEL表达式来指定缓存键,例如:@Cacheable(key = "#id"),其中id是方法的参数。

    condition:指定一个SpEL表达式,用于判断是否执行缓存操作。只有当表达式的结果为true时,才会执行缓存操作。例如:@Cacheable(condition = "#result != null"),表示只有当方法的返回结果不为空时,才会执行缓存操作。

    unless:指定一个SpEL表达式,用于判断是否不执行缓存操作。只有当表达式的结果为false时,才会执行缓存操作。例如:@Cacheable(unless = "#result == null"),表示只有当方法的返回结果为空时,才不会执行缓存操作。

    keyGenerator:指定一个自定义的缓存键生成器,用于生成缓存的键。可以实现KeyGenerator接口来自定义缓存键的生成逻辑。
    使用@Cacheable注解可以将方法的返回结果缓存起来,提高系统的响应速度和并发处理能力。通过指定缓存名称、缓存键、条件和键生成器等属性,可以对缓存进行更加精细的控制。同时,需要注意权衡缓存的一致性和实时性,避免数据不一致或过期的问题。

    基本用法示例:

    @Cacheable(value = "clz" ,key = "'cid'+#cid")

     用法内属性解释: 

    • value: 用于指定缓存的名称,你可以在配置文件中定义不同的缓存管理器,这里的"value"指定了要使用的缓存。
    • key属性:使用SpEL表达式,"'cid'+#cid"生成缓存的键。这个键将由方法的cid参数的值动态生成。如果方法被调用时传入不同的cid值,将会生成不同的缓存键,因此不同的cid值将会对应不同的缓存项。这允许你在不同的上下文中存储和获取缓存数据。

    2.2. @CachePut 

    @CachePut 是 Spring Framework 中的一个注解,用于将方法的返回值存储到缓存中,通常用于更新缓存中的数据。

    @CachePut方法作用:

    1. 更新缓存数据:@CachePut 用于强制将方法的返回值存储到缓存中,无论缓存中是否已存在相同的键。这对于确保缓存中的数据是最新的非常有用,特别是在需要手动更新缓存数据时。
    2. 动态生成缓存键:@CachePut 允许你使用 Spring Expression Language (SpEL) 表达式来动态生成缓存项的键。这使得你可以根据方法的参数或其他条件来生成缓存键,以确保不同的缓存项具有不同的键。
    3. 条件性更新:@CachePut 支持 condition 和 unless 属性,可以根据条件来控制是否执行缓存更新操作。这使你可以在特定条件下才更新缓存,从而更加灵活地管理缓存。
    4. 清空指定缓存项:通过配置 allEntries 属性为 true,可以清空与指定缓存相关的所有缓存项,而不仅仅是更新一个特定的缓存项。
    5. 控制更新时机:使用 beforeInvocation 属性,你可以控制是在方法执行之前还是方法执行成功后触发缓存更新。

    注:

    • @CachePut 注解用于更新缓存中的数据,不同于 @Cacheable,它会执行方法体,并将方法返回的值存入缓存中,以确保缓存中的数据是最新的。
    • 如果缓存中的数据不存在,@CachePut将创建一个新的缓存项。

     基本用法示例:

    @CachePut(value = "xx",key = "'cid:'+#cid")

    用法内属性解释: 

    • @CachePut注解用于将方法的返回值存储到缓存中,通常用于更新缓存中的数据。
    • @Cacheable不同,它不会检查缓存中是否已存在相同的键,而是直接将方法的返回值存入缓存,以确保缓存中的数据是最新的。
    • 这对于更新缓存项非常有用,以确保缓存中的数据与后端数据保持同步。

    2.3. @CacheEvict

    @CacheEvict 是 Spring Framework 中的一个注解,用于从缓存中移除指定的缓存项或清空整个缓存。

    @CacheEvict方法作用:

     

    1. 清空指定缓存项:你可以使用 @CacheEvict 来清空一个或多个特定缓存中的缓存项,以确保缓存中的数据保持最新或满足特定条件时清除缓存。
    2. 条件性清除:@CacheEvict 支持 condition 和 unless 属性,可以根据条件来控制是否执行缓存清除操作。这允许你在满足特定条件时才清除缓存,从而更加灵活地管理缓存。
    3. 清空整个缓存:通过设置 allEntries 属性为 true,你可以清空整个缓存,而不仅仅是清除特定的缓存项。这对于需要在某些情况下全局清空缓存的场景非常有用。
    4. 控制清除时机:使用 beforeInvocation 属性,你可以控制是在方法执行之前还是方法执行成功后触发缓存清除操作。
    5. 清除缓存的多个条目:可以通过 key 属性设置一个缓存键表达式,以删除匹配特定键模式的缓存项。这允许你按一定的模式来删除缓存项。

    @CacheEvict 注解的主要作用是从缓存中移除指定的缓存项或清空整个缓存,以确保缓存中的数据保持最新或根据条件来清除缓存。它提供了多个属性,使你可以根据需要来配置清除缓存的方式和时机,以满足特定的业务需求。

     基本用法示例:

    @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)

     用法内属性解释:

    • value 属性:设置为 "xx",表示要清除名为 "xx" 的缓存。通常,你需要在配置中定义相应的缓存管理器,以确保它与这个缓存名称关联。
    • key 属性:使用 SpEL 表达式 "'cid:'+#cid" 来生成缓存项的键。这个键将由方法的 cid 参数值动态生成,前缀为 "cid:"。这将导致匹配 "cid:" 后跟 cid 参数值的缓存项被清除。
    • allEntries 属性:设置为 true,表示清除整个缓存。如果 allEntries 设置为 true,则会忽略 key 属性,而是清除指定缓存中的所有缓存项。在这个示例中,不管 cid 参数的值如何,都会清空名为 "xx" 的缓存中的所有内容。

    2.4.总结

    @Cacheable@CachePut 和 @CacheEvict 是 Spring Framework 中用于管理缓存的注解,它们有不同的作用和行为:

    • @Cacheable:
    1. 作用:@Cacheable 用于声明一个方法的返回值可以被缓存,即当方法被调用时,Spring会首先检查缓存,如果缓存中存在相应的结果,就会返回缓存的值而不执行方法体。
    2. 主要用途:提高性能,避免重复执行相同的方法,适用于读取操作,不用于更新数据
    3. 配置:可以指定缓存的名称、缓存键、条件等。
    • @CachePut:
    1. 作用:@CachePut 用于强制将方法的返回值存储到缓存中,通常用于更新缓存中的数据。
    2. 主要用途:更新缓存,将方法返回的值放入缓存,适用于写入操作。
    3. 配置:可以指定缓存的名称、缓存键、条件等。
    • @CacheEvict:
    1. 作用:@CacheEvict 用于从缓存中移除指定的缓存项或清空整个缓存。
    2. 主要用途:清除缓存项,使缓存中的数据保持最新或根据条件来清除缓存。
    3. 配置:可以指定缓存的名称、缓存键、条件、是否清空整个缓存等。

    区别总结:

    • @Cacheable 用于缓存方法的返回值,避免重复执行方法,适用于读取操作。
    • @CachePut 用于将方法的返回值存储到缓存中,通常用于更新缓存中的数据,适用于写入操作。
    • @CacheEvict 用于清除缓存项,可以清空指定缓存项或整个缓存。

    关于使用: 

    这些注解可以根据具体的业务需求来组合使用,以实现灵活的缓存策略。例如,可以使用 @Cacheable 缓存读取操作的结果,使用 @CachePut 更新缓存项,使用 @CacheEvict 清除缓存中的数据,以满足不同的缓存需求。

    三.redis的击穿穿透雪崩

    当涉及到 Redis 时,"击穿"、"穿透"和"雪崩"是一些常见的问题,涉及缓存系统的高可用性和稳定性。下面我将对这三个问题进行详细解释:

    • 击穿(Cache Breakdown):

    出现在热点数据失效的情况下。当一个特定的键失效并且接收到了大量的并发请求,这些请求会绕过缓存直接访问数据库,导致数据库压力骤增。这是因为缓存失效后,下一次访问时无法从缓存中获取数据,而必须去数据库中获取。

    • 穿透(Cache Penetration):

    当恶意用户请求一个不存在于缓存和数据库中的键时,缓存系统无法提供数据,这些请求会直接访问数据库。这可能会导致数据库负载增加,甚至引发拒绝服务攻击。为了应对穿透问题,可以在查询不存在键时设置一个空值或者采用布隆过滤器等方法来过滤无效请求。

    • 雪崩(Cache Avalanche):

    当缓存中大量的键同时失效,导致大量请求直接访问后端数据库,使得数据库压力骤增,甚至崩溃。这通常是由于缓存中的数据设置了相同的过期时间,导致在同一时间大量的键失效,引发雪崩效应。为了避免雪崩问题,可以采用随机的过期时间、添加热点数据的预加载等策略。

    为了应对这些问题,可以采取以下一些解决方案:

    • 对于击穿问题,可以使用互斥锁或者设置短暂的过期时间来保护热点数据,确保缓存中有有效的数据。
    • 对于穿透问题,可以使用布隆过滤器等技术来过滤无效请求,确保缓存系统只处理有效的请求。
    • 对于雪崩问题,可以采用分布式缓存、多级缓存、缓存预热等策略,保证缓存中的数据分布均匀,避免大量数据同时失效。

                    好啦今天就到这里了哦!!希望能帮到你哦!! 

  • 相关阅读:
    Kafka不仅是消息队列而是一个分布式消息处理平台
    layui 富文本编辑器layedit 以及 图片转base64前端页面显示
    从零开始,打造自己的专属游戏世界!
    C++智能指针
    codeforces每日5题(均1500)-第二十五天
    LeetCode48旋转图像
    如何直击固定资产管理的难题?
    操作系统与shell
    java设计模式3,里氏替换原则
    Linux初识+环境部署
  • 原文地址:https://blog.csdn.net/m0_74915426/article/details/134353702