SSM项目与Redis整合以及Redis注解式开发以及Redis击穿穿透雪崩

编程入门 行业动态 更新时间:2024-10-07 22:23:38

SSM项目与Redis整合以及Redis<a href=https://www.elefans.com/category/jswz/34/1768912.html style=注解式开发以及Redis击穿穿透雪崩"/>

SSM项目与Redis整合以及Redis注解式开发以及Redis击穿穿透雪崩

目录

前言

一、SSM项目整合Redis

1.导入pom依赖

2.Spring-redis相关配置

3.Spring上下文配置 

二、redis注解式缓存

1.@Cacheable 注解

2.@CachePut 注解

3.@CacheEvict 注解

三、redis击穿、穿透、雪崩

1. 缓存击穿

2. 缓存穿透

3. 缓存雪崩


前言

当将SSM项目与Redis整合,并使用Redis注解式开发时,避免缓存击穿、缓存穿透和缓存雪崩是至关重要的。下面我将为你写一篇详细的博客,涵盖这些内容。

一、SSM项目整合Redis

在SSM项目中,将Redis作为缓存,可以大大提高系统的性能和吞吐量。整合过程主要包括引入依赖、配置Redis连接等进行进行操作。

1.导入pom依赖

<redis.version>2.9.0</redis.version>
<redis.spring.version>1.7.1.RELEASE</redis.spring.version><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>${redis.version}</version>
</dependency>
<dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>${redis.spring.version}</version>
</dependency>

2.Spring-redis相关配置

配置文件redis.properties

redis.hostName=192.168.195.139
redis.port=6379
redis.password=123456
redis.timeout=10000
redis.maxIdle=300
redis.maxTotal=1000
redis.maxWaitMillis=1000
redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000
redis.testOnBorrow=true
redis.testWhileIdle=true
redis.expiration=3600

Spring-redis.xml 

  1. 注册 redis.properties
  2. 配置数据源
  3. 连接工厂
  4. 配置序列化
  5. 配置redis的key生成策略
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:xsi=""xmlns:context=""xmlns:cache=""xsi:schemaLocation="://www.springframework/schema/beans/spring-beans.xsd://www.springframework/schema/context/spring-context.xsd://www.springframework/schema/cache/spring-cache.xsd"><!-- 1. 引入properties配置文件 --><!--<context:property-placeholder location="classpath:redis.properties" />--><!-- 2. redis连接池配置--><bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"><!--最大空闲数--><property name="maxIdle" value="${redis.maxIdle}"/><!--连接池的最大数据库连接数  --><property name="maxTotal" value="${redis.maxTotal}"/><!--最大建立连接等待时间--><property name="maxWaitMillis" value="${redis.maxWaitMillis}"/><!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)--><property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/><!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3--><property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/><!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1--><property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/><!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个--><property name="testOnBorrow" value="${redis.testOnBorrow}"/><!--在空闲时检查有效性, 默认false  --><property name="testWhileIdle" value="${redis.testWhileIdle}"/></bean><!-- 3. redis连接工厂 --><bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"destroy-method="destroy"><property name="poolConfig" ref="poolConfig"/><!--IP地址 --><property name="hostName" value="${redis.hostName}"/><!--端口号  --><property name="port" value="${redis.port}"/><!--如果Redis设置有密码  --><property name="password" value="${redis.password}"/><!--客户端超时时间单位是毫秒  --><property name="timeout" value="${redis.timeout}"/></bean><!-- 4. redis操作模板,使用该对象可以操作redishibernate课程中hibernatetemplete,相当于session,专门操作数据库。--><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"><property name="connectionFactory" ref="connectionFactory"/><!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  --><property name="keySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property><property name="valueSerializer"><bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/></property><property name="hashKeySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property><property name="hashValueSerializer"><bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/></property><!--开启事务  --><property name="enableTransactionSupport" value="true"/></bean><!--  5.配置缓存管理器  --><bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"><constructor-arg name="redisOperations" ref="redisTemplate"/><!--redis缓存数据过期时间单位秒--><property name="defaultExpiration" value="${redis.expiration}"/><!--是否使用缓存前缀,与cachePrefix相关--><property name="usePrefix" value="true"/><!--配置缓存前缀名称--><property name="cachePrefix"><bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix"><constructor-arg index="0" value="-cache-"/></bean></property></bean><!--6.配置缓存生成键名的生成规则--><bean id="cacheKeyGenerator" class="com.ctb.ssm.redis.CacheKeyGenerator"></bean><!--7.启用缓存注解功能--><cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
</beans>

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

3.Spring上下文配置 

SpringContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:xsi=""xsi:schemaLocation=" .xsd"><!--1. 引入外部多文件方式 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /><property name="ignoreResourceNotFound" value="true" /><property name="locations"><list><value>classpath:jdbc.properties</value><value>classpath:redis.properties</value></list></property></bean><!--引入mybatis的相关配置文件--><import resource="applicationContext-mybatis.xml"></import><!--spring管理ehcache对应配置文件--><import resource="applicationContext-ehcache.xml"></import><!--spring管理redis对应配置文件--><import resource="applicationContext-redis.xml"></import><import resource="applicationContext-shiro.xml"/>
</beans>

二、redis注解式缓存

首先需要一个缓冲策略类,用于存储信息

package com.ctb.ssm.redis;import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.util.ClassUtils;import java.lang.reflect.Array;
import java.lang.reflect.Method;@Slf4j
public class CacheKeyGenerator implements KeyGenerator {// custom cache keypublic static final int NO_PARAM_KEY = 0;public static final int NULL_PARAM_KEY = 53;@Overridepublic Object generate(Object target, Method method, Object... params) {StringBuilder key = new StringBuilder();key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");if (params.length == 0) {key.append(NO_PARAM_KEY);} else {int count = 0;for (Object param : params) {if (0 != count) {//参数之间用,进行分隔key.append(',');}if (param == null) {key.append(NULL_PARAM_KEY);} else if (ClassUtils.isPrimitiveArray(param.getClass())) {int length = Array.getLength(param);for (int i = 0; i < length; i++) {key.append(Array.get(param, i));key.append(',');}} else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {key.append(param);} else {//Java一定要重写hashCode和eqaulskey.append(param.hashCode());}count++;}}String finalKey = key.toString();
//        IEDA要安装lombok插件log.debug("using cache key={}", finalKey);return finalKey;}
}

1.@Cacheable 注解

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

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

 @Cacheable测试代码

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

测试类

package com.ctb.shiro;import com.ctb.ssm.biz.ClazzBiz;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class ClazzBizTest {@Autowiredprivate ClazzBiz clazzBiz;@Testpublic void test1(){System.out.println(clazzBiz.selectByPrimaryKey(10));System.out.println(clazzBiz.selectByPrimaryKey(10));}}

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

2.@CachePut 注解

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

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

@CachePut测试代码

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

测试类

@Testpublic void test2(){
//        测试 Cacheput 中的 keySystem.out.println(clazzBiz.selectByPrimaryKey(4));System.out.println(clazzBiz.selectByPrimaryKey(4));}

结果:只存不取

3.@CacheEvict 注解

用来清除用在本方法或者类上的缓存数据(用在哪里清除哪里)

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

@CacheEvict测试代码

 @CacheEvict(value = "user-clz-put",allEntries = true)   // 删除以 user-clz-put开头的 缓存int deleteByPrimaryKey(Integer cid);

测试类

 @Testpublic void test3(){
//        测试 CacheEvict 中的 keyclazzBiz.deleteByPrimaryKey(4);}

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

三、redis击穿、穿透、雪崩

1. 缓存击穿

问题描述:缓存击穿是指当某个热点数据失效后,大量并发请求直接打到数据库上,造成数据库压力激增。

解决方案

  • 使用互斥锁(Mutex Lock)或分布式锁(Distributed Lock)来保护对数据库的访问,确保只有一个线程可以进行数据库查询操作。
  • 针对热点数据,设置永不过期的缓存策略,或者使用预加载机制,在数据失效之前提前刷新缓存。

2. 缓存穿透

问题描述:缓存穿透是指恶意或不存在的请求经过缓存直接访问数据库,由于缓存中没有相关数据,每次请求都会直接查询数据库,导致数据库负载过大。

解决方案

  • 使用布隆过滤器(Bloom Filter)等技术来识别不存在的数据,避免对数据库造成压力。
  • 对不存在的数据也进行缓存,但设置较短的过期时间,避免无效数据长时间存放在缓存中。

3. 缓存雪崩

问题描述:缓存雪崩是指当缓存中大量的数据同时失效,导致大量请求直接打到数据库上,引起数据库压力骤增。

解决方案

  • 设置缓存数据过期时间错开,通过随机的方式为缓存设置过期时间,避免大量缓存同时失效。
  • 使用热点数据永不过期的方式,或者预先设置好热点数据的缓存过期时间,确保重要数据的稳定性。

更多推荐

SSM项目与Redis整合以及Redis注解式开发以及Redis击穿穿透雪崩

本文发布于:2023-11-16 02:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1611752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注解   项目   SSM   Redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!