• SSM之spring注解式缓存redis


    目录

    1.Spring整合redis

    1.1.导入相关pom依赖

    1.2.添加相关的配置文件

    1.3.整合配置文件

    1.4.测试

    2.reids的注解式开发

    2.1.@Cacheable

    2.2.@CachePut

    2.3.@CacheEvict

    3.redis击穿穿透雪崩*****

    3.1.什么是击穿?

    解决方案:

    3.2.什么是穿透?

    解决方案:

    3.3.什么是雪蹦?

    解决方案:


    1.Spring整合redis

    1.1.导入相关pom依赖

    定义redis版本:

      2.9.0
      1.7.1.RELEASE
    

    redis整合:

    
      redis.clients
      jedis
      ${redis.version}
    
    
      org.springframework.data
      spring-data-redis
      ${redis.spring.version}
    

    1.2.添加相关的配置文件

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

    注意:要进行修改,没有的要进行添加

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

    注意:redis.properties与jdbc.properties在与Spring做整合时会发生冲突;所以引入配置文件的地方要放到SpringContext.xml中

    1.3.整合配置文件

    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>

    1.4.测试

     能访问就可以啦!!!

    2.reids的注解式开发

    准备工作:打开虚拟机连接Redis

    2.1.@Cacheable

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

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

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

    @Cacheable 的测试代码

    @Cacheable(value = "user-clz",key = "'clz:'+#cid",condition = "#cid < 5")
    Clazz selectByPrimaryKey(Integer cid);

    测试类:

    @Test
        public void test1(){
    //        测试 Cacheable 中的value,以及缓存的应用体现
    //        System.out.println(clazzBiz.selectByPrimaryKey(1));
    //        System.out.println("======================================");
    //        System.out.println(clazzBiz.selectByPrimaryKey(1));

    //        测试 Cacheable 中的 key
    //        System.out.println(clazzBiz.selectByPrimaryKey(3));
    //        System.out.println("======================================");
    //        System.out.println(clazzBiz.selectByPrimaryKey(3));

    //        测试 Cacheable 中的 condition
            System.out.println(clazzBiz.selectByPrimaryKey(4));
            System.out.println("======================================");
            System.out.println(clazzBiz.selectByPrimaryKey(4));
        }

    测试结果:redis中有数据,则访问redis;如果没有数据,则访问MySQL;

    2.2.@CachePut

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

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

    测试:

    @CachePut(value = "user-clz-put")
    Clazz selectByPrimaryKey(Integer cid);

    @Test
        public void test2(){
    //        测试 Cacheput 中的 key
            System.out.println(clazzBiz.selectByPrimaryKey(4));
            System.out.println("======================================");
            System.out.println(clazzBiz.selectByPrimaryKey(4));
        }

    测试结果:只存不取

    2.3.@CacheEvict

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

    测试:

    //    @CacheEvict(value = "user-clz-put",key = "'clz:'+#cid")   删除指定的缓存数据
        @CacheEvict(value = "user-clz-put",allEntries = true)   // 删除以 user-clz-put开头的 缓存
        int deleteByPrimaryKey(Integer cid);

     @Test
        public void test3(){
    //        测试 CacheEvict 中的 key
            clazzBiz.deleteByPrimaryKey(2);
        }

    测试结果:可以配置删除指定缓存数据,也可以删除符合规则的所有缓存数据;

    3.redis击穿穿透雪崩*****

    学习网址:https://zhuanlan.zhihu.com/p/348552497

    3.1.什么是击穿?

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

    解决方案:

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

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

    3.2.什么是穿透?

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

    解决方案:

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

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

    3.3.什么是雪蹦?

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

    解决方案:

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

    今天就分享到这里!!!

  • 相关阅读:
    WPF自定义控件与样式(5)-Calendar/DatePicker日期控件自定义样式及扩展
    06 - ip route和route -n的区别
    python面相对象基础语法
    PROSAIL模型的植被参数光学遥感反演
    信息学奥赛一本通:2038:【例5.5】最大数位置
    Qt实现一个简易截图工具(支持缩放、移动、保存、复制到粘贴板)
    MySQL查询性能优化七种武器之索引潜水
    【操作系统】32进制小数转10进制
    JavaScript随机整数案例
    uni-app(三):离线打包与插件引用(Android)
  • 原文地址:https://blog.csdn.net/m0_68211831/article/details/127577794