当前位置:首页 >> 编程语言 >> 【Redis】Redis整合SSMRedis中的缓存穿透、雪崩、击穿的原因以及解决方案(详解),松下 FX7

【Redis】Redis整合SSMRedis中的缓存穿透、雪崩、击穿的原因以及解决方案(详解),松下 FX7

cpugpu芯片开发光刻机 编程语言 1
文件名:【Redis】Redis整合SSMRedis中的缓存穿透、雪崩、击穿的原因以及解决方案(详解),松下 FX7 【Redis】Redis整合SSMRedis中的缓存穿透、雪崩、击穿的原因以及解决方案(详解)

目录:

目录

一,SSM整合redis

二,redis注解式缓存

三,Redis中的缓存穿透、雪崩、击穿的原因以及解决方案(附图)


一,SSM整合redis

1.原因:

 整合SSM和Redis可以提升系统的性能、可伸缩性和可靠性,在分布式环境下更好地支持会话管理、消息队列和分布式锁等功能。

2.步骤:可以参考SSM整合mysql

导入pom依赖在Maven中添加Redis的依赖

<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.2.spring-redis.xml的相关配置

redis.properties

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

spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:cache="http://www.springframework.org/schema/cache"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/cachehttp://www.springframework.org/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.zking.ssm.redis.CacheKeyGenerator"></bean><!--7.启用缓存注解功能--><cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/></beans>

2.3.修改applicationContext.xml

如果spring配置文件中需要配置两个及以上的properties文件则需要在applicationContext.xml中进行配置处理,否则会出现覆盖的情况。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"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"><!--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><!-- 随着后续学习,框架会越学越多,不能将所有的框架配置,放到同一个配制间,否者不便于管理 --><import resource="applicationContext-mybatis.xml"></import><import resource="spring-redis.xml"></import><import resource="applicationContext-shiro.xml"></import></beans>

2.4.配置redis的key生成策略

CacheKeyGenerator.java

package com.zking.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;@Slf4jpublic 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;}}

二,redis注解式缓存

关于什么是Redis注解式:

注解式缓存是一种通过在方法上添加特定的注解来实现自动缓存的机制。在Java开发中,我们可以使用Spring框架提供的@Cacheable、@CachePut和@CacheEvict等注解来实现对Redis的缓存操作。

@Cacheable注解:

作用:标记方法的返回值可以被缓存,并且在下次调用该方法时,会直接从缓存中获取结果,而不会执行方法体内的逻辑。示例代码:@Cacheable(value = "myCache", key = "#id")public User getUserById(String id) {// 从数据库或其他数据源获取用户信息的逻辑return user;}

解释:以上代码表示将方法的返回值以键值对的形式缓存在名为"myCache"的缓存中,缓存的key由参数"id"决定。

@CachePut注解:

作用:标记方法的返回值需要更新缓存,即每次调用方法都会执行方法体内的逻辑,并将返回值存入缓存。示例代码: @CachePut(value = "myCache", key = "#user.id")public User updateUser(User user) {// 更新用户信息的逻辑return user;} 解释:以上代码表示每次调用该方法都会执行方法体内的逻辑,然后将返回值以键值对的形式存入名为"myCache"的缓存中。缓存的key由user.id决定。

@CacheEvict注解:

作用:标记方法会清除缓存中的指定数据。示例代码:@CacheEvict(value = "myCache", key = "#id")public void deleteUser(String id) {// 删除用户信息的逻辑}

解释:以上代码表示调用该方法时会从名为"myCache"的缓存中移除key为参数"id"对应的缓存数据。

通过使用这些注解,我们可以更加方便地实现对Redis的缓存操作,减少了手动管理缓存的复杂性。但需要注意的是,使用注解式缓存时,需要确保被缓存的方法的输入参数和返回值类型是可序列化的,以便在Redis中进行存储和读取。

此外,还可以通过配置Spring框架的缓存管理器、缓存策略等来进一步优化和配置缓存行为。具体的配置和使用细节可以参考Spring框架的文档和教程。

三,Redis中的缓存穿透、雪崩、击穿的原因以及解决方案(附图)

缓存穿透(Cache Penetration):

原因当请求查询一个不存在于缓存和数据库中的数据时,每次查询都会直接访问数据库,导致对数据库的频繁访问,增加数据库负载。情景:客户端发送大量的不可响应的请求:比如发送一个id为-999的用户解决方案: 布隆过滤器(Bloom Filter):用于判断请求的数据是否存在于缓存或数据库中。使用布隆过滤器可以快速过滤掉一部分不存在的数据,避免对数据库的无效查询。空值缓存(Null Object Caching):将不存在的数据也缓存起来,但设置一个较短的过期时间,以便下次查询时可以从缓存中获取。

注意事项:

使用空值作为缓存的时候,key设置的过期时间不能太长,防止占用太多redis资源 对空值缓存是一种被动的防御方式,当遇到黑客暴力请求很多不存在的数据就需要写入大量的null值到Redis中,可能导致Redis内存占用不足的情况 使用布隆过滤器,可以在用户访问的时候判断该资源是否存在,不存在则直接拒绝访问 布隆过滤器是有一定的误差,所以一般需要配合一些接口流量的限制(规定用户在一段时间内访问的频率)、权限校验、黑名单等来解决缓存穿透的问题

缓存雪崩(Cache Avalanche):

原因当缓存中的大量数据同时过期或失效时,所有请求都会直接访问数据库,导致数据库压力骤增,甚至导致数据库宕机。解决方案: 随机过期时间(Randomized Expiration):为缓存中的数据设置随机的过期时间,以避免大量数据同时过期。并发控制(Concurrency Control):使用分布式锁或互斥机制,确保只有一个线程可以重新加载缓存数据,避免重复查询。

缓存击穿(Cache Miss):

原因当某个热点数据过期或失效时,大量请求同时涌入,导致并发查询数据库,增加数据库压力。解决方案: 互斥锁(Mutex Lock):在缓存失效的情况下,使用互斥锁来确保只有一个请求可以查询数据库,并将查询结果进行缓存,其他请求等待缓存更新后再获取数据。提前加载(Preloading):提前加载热点数据到缓存中,并设置较长的过期时间,以避免热点数据过期后被击穿。

协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接