Redis注解式开发团结SSM项目使用与Quartz框架先容以及击穿、穿透、雪崩标题 ...

种地  论坛元老 | 2024-10-6 23:22:00 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1091|帖子 1091|积分 3273

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
目录
一、SSM项目整合Redis
1.1 导入pom依赖
1.2 spring-redis.xml
1.3 spring上下文配置 
 
二、Redis注解式开发
2.1 Cacheable 注解
2.2 自界说策略
2.3 CachePut 注解
 
三、Redis中缓冲、击穿、穿透、雪崩标题解决
3.1 缓冲标题 —— Quartz 框架 
3.2 常见的三种标题解决方案 


一、SSM项目整合Redis

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

  1.   <properties>   
  2.     <redis.version>2.9.0</redis.version>
  3.     <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
  4.   </properties>
  5.   <dependencies>
  6.     <dependency>
  7.       <groupId>redis.clients</groupId>
  8.       <artifactId>jedis</artifactId>
  9.       <version>${redis.version}</version>
  10.     </dependency>
  11.     <dependency>
  12.       <groupId>org.springframework.data</groupId>
  13.       <artifactId>spring-data-redis</artifactId>
  14.       <version>${redis.spring.version}</version>
  15.     </dependency>
  16.   </dependencies>
复制代码

1.2 spring-redis.xml


  • 注册 redis.properties
  • 配置数据源
  • 连接工厂
  • 配置序列化
  • 配置redis的key生成策略
  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"
  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.     <!-- 1. 引入properties配置文件 -->
  13.     <context:property-placeholder location="classpath:redis.properties" />
  14.     <!-- 2. redis连接池配置-->
  15.     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  16.         <!--最大空闲数-->
  17.         <property name="maxIdle" value="300"/>
  18.         <!--连接池的最大数据库连接数  -->
  19.         <property name="maxTotal" value="${redis.maxTotal}"/>
  20.         <!--最大建立连接等待时间-->
  21.         <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
  22.         <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->
  23.         <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
  24.         <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
  25.         <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
  26.         <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->
  27.         <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
  28.         <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->
  29.         <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
  30.         <!--在空闲时检查有效性, 默认false  -->
  31.         <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
  32.     </bean>
  33.     <!-- 3. redis连接工厂 -->
  34.     <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
  35.           destroy-method="destroy">
  36.         <property name="poolConfig" ref="poolConfig"/>
  37.         <!--IP地址 -->
  38.         <property name="hostName" value="${redis.hostName}"/>
  39.         <!--端口号  -->
  40.         <property name="port" value="${redis.port}"/>
  41.         <!--如果Redis设置有密码  -->
  42.         <property name="password" value="${redis.password}"/>
  43.         <!--客户端超时时间单位是毫秒  -->
  44.         <property name="timeout" value="${redis.timeout}"/>
  45.     </bean>
  46.     <!-- 4. redis操作模板,使用该对象可以操作redis
  47.         hibernate课程中hibernatetemplete,相当于session,专门操作数据库。
  48.     -->
  49.     <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  50.         <property name="connectionFactory" ref="connectionFactory"/>
  51.         <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->
  52.         <property name="keySerializer">
  53.             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
  54.         </property>
  55.         <property name="valueSerializer">
  56.             <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
  57.         </property>
  58.         <property name="hashKeySerializer">
  59.             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
  60.         </property>
  61.         <property name="hashValueSerializer">
  62.             <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
  63.         </property>
  64.         <!--开启事务  -->
  65.         <property name="enableTransactionSupport" value="true"/>
  66.     </bean>
  67.     <!--  5.配置缓存管理器  -->
  68.     <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
  69.         <constructor-arg name="redisOperations" ref="redisTemplate"/>
  70.         <!--redis缓存数据过期时间单位秒-->
  71.         <property name="defaultExpiration" value="${redis.expiration}"/>
  72.         <!--是否使用缓存前缀,与cachePrefix相关-->
  73.         <property name="usePrefix" value="true"/>
  74.         <!--配置缓存前缀名称-->
  75.         <property name="cachePrefix">
  76.             <bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix">
  77.                 <constructor-arg index="0" value="-cache-"/>
  78.             </bean>
  79.         </property>
  80.     </bean>
  81.     <!--6.配置缓存生成键名的生成规则-->
  82.     <bean id="cacheKeyGenerator" class="com.zking.ssm.redis.CacheKeyGenerator"></bean>
  83.     <!--7.启用缓存注解功能-->
  84.     <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
  85. </beans>
复制代码
  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
复制代码

1.3 spring上下文配置 

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注解式开发

首先需要一个缓冲策略类,用于储存信息
  1. package com.ycxw.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. }
复制代码
 
2.1 Cacheable 注解

1、界说查询接口使用Cacheable注解
   Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来实行该方法时可以直接从缓存中获取结果,而不需要再次实行该方法。Spring在缓存方法的返回值时是以键值对举行缓存的,值就是方法的返回结果。
  1. package com.ycxw.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.     @Cacheable("clz")
  9.     Clazz selectByPrimaryKey(Integer cid);
  10. }
复制代码
 2、编写测试类
  1. package com.ycxw.shiro;
  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. @RunWith(SpringJUnit4ClassRunner.class)
  9. @ContextConfiguration(locations={"classpath:applicationContext.xml"})
  10. public class ClazzBizTest {
  11.     @Autowired
  12.     private ClazzBiz clazzBiz;
  13.     @Test
  14.     public void test1(){
  15.         System.out.println(clazzBiz.selectByPrimaryKey(10));
  16.         System.out.println(clazzBiz.selectByPrimaryKey(10));
  17.     }
  18. }
复制代码
  第一次运行时:(查询两次)
  

   
  第二次运行时:(无查询语句)
  
 
  再次运行相同的数据时不再查询了,直接从缓冲中拿取数据:
  

  

2.2 自界说策略

@Cacheable可以指定三个属性,value、key和condition。 
   我可界说key值来修改我们保存到redis缓冲的key值,而且可通过condition来制定什么时候需要缓冲,进一步优化性能。
  自界说策略,如果查询的cid大于6才举行缓冲 
  1. package com.ycxw.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.     @Cacheable(value = "clz",key = "'cid:'+#cid",condition = "#cid > 6")
  9.     Clazz selectByPrimaryKey(Integer cid);
  10. }
复制代码

2.3 CachePut 注解

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


  • Cacheable:会在redis中存储数据,同时也会读取数据
  • CachePut:只会在redis储存数据,不会举行读取操作
  1. package com.ycxw.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.     @CachePut(value = "clz",key = "'cid:'+#cid",condition = "#cid > 6")
  9.     Clazz selectByPrimaryKey(Integer cid);
  10. }
复制代码
测试:
  1. public class ClazzBizTest {
  2.     @Autowired
  3.     private ClazzBiz clazzBiz;
  4.     @Test
  5.     public void test1(){
  6.         System.out.println(clazzBiz.selectByPrimaryKey(9));
  7.         System.out.println(clazzBiz.selectByPrimaryKey(9));
  8.     }
  9. }
复制代码

   不管运行多少次,它还是会查询数据库,即便已经将数据存储到redis中
  

  
三、Redis中缓冲、击穿、穿透、雪崩标题解决

3.1 缓冲标题 —— Quartz 框架 

        如今模仿一个场景:我在某系统中增加了一条数据,在主界面中会显示该条数据。而数据是从缓冲中拿取的,而新增的数据并没有立即添加到缓冲中。那我们怎样保证redis数据与数据库数据的一致性呢?

方案一:手动刷新数据同步策略
        这样我们每次添加了新的数据,需要手动点击刷新缓冲键,显然这个对管理者不便的。

方案二:利用Quartz作业调度框架,定时刷新任务
           Quartz是一个开源的作业调度框架,用于在Java应用步伐中实现任务调度和定时任务管理。它提供了一种简单而强大的方式来安排和实行各种类型的作业,包括定时任务、周期性任务和异步任务。
          Quartz框架的焦点概念是作业(Job)和触发器(Trigger)。作业是要实行的任务,而触发器界说了作业实行的时间和频率。通过配置作业和触发器,可以实现机动的任务调度和实行。
  在Redis中,它自己并没有直接使用Quartz框架。然而,我们可以团结使用QuartzRedis来实现一些特定的功能,例如:


  • 使用Quartz调度任务,将任务的实行结果存储到Redis中,以便其他系统或模块可以读取和处置惩罚。
  • 使用Quartz定时清理Redis中的过期数据,以确保Redis的存储空间得到有用利用。
  • 使用Quartz定时刷新Redis中的缓存数据,以保持数据的最新性。
  • 使用Quartz和Redis实现分布式锁机制,确保在多个节点上的任务调度不会发生辩说。

3.2 常见的三种标题解决方案 

1、击穿(Cache Miss) 击穿指的是在高并发环境下,当一个缓存键(key)不存在于缓存中,但是被大量请求同时查询时,这些请求会直接访问数据库,导致数据库压力过大。这种环境下,缓存无法发挥作用,而且数据库可能会因此而瓦解。
解决方案:


  • 使用互斥锁(Mutex Lock)或分布式锁(Distributed Lock)来掩护数据库访问,确保只有一个请求能够访问数据库,其他请求等待结果。
  • 在缓存中设置短暂的空值(Null Value),以防止大量请求同时查询同一个缓存键。
 
2、穿透(Cache Penetration) 穿透指的是当一个缓存键不存在于缓存中,而且被大量请求同时查询时,这些请求都会直接访问数据库,导致数据库压力过大。与击穿不同的是,穿透是由于查询的键根本不存在于缓存中。
解决方案:


  • 在查询数据库之前,可以添加一个布隆过滤器(Bloom Filter)来快速判断查询的键是否存在于缓存中。如果不存在,可以直接返回空结果,而不是访问数据库。
  • 对于查询结果为空的环境,也可以将空结果缓存一段时间,以克制频仍查询数据库。
 
3、雪崩(Cache Avalanche) 雪崩指的是在缓存中大量的缓存键同时过期或失效,导致大量请求直接访问数据库,造成数据库压力过大,甚至瓦解。
解决方案:


  • 设置缓存键的过期时间时,可以引入随机值,使得缓存键的过期时间分散开来,克制大量缓存键同时过期。
  • 使用热门数据预加载(Cache Pre-warming)策略,提前加载热门数据到缓存中,淘汰缓存键同时失效的可能性。
  • 使用多级缓存架构,将缓存分为多个层级,以低沉团体缓存失效的风险。
 
        总结: 在解决这些标题时,我们需要综合考虑系统的并发性、可用性和性能。通过公道的缓存策略、锁机制、预加载与使用调度框架等本领,可以有用地解决Redis中的击穿、穿透和雪崩标题,进步系统的稳定性和性能。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

种地

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表