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

news/2025/2/12 20:57:21/

目录:

目录

一,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.1
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

<?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;@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;}
}

二,redis注解式缓存

关于什么是Redis注解式:

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

  1. @Cacheable注解:

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

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

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

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

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

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

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

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

  1. 缓存穿透(Cache Penetration):

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

        注意事项:

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

  2. 缓存雪崩(Cache Avalanche):

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

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


http://www.ppmy.cn/news/1201365.html

相关文章

自定义element-ui plus 函数式调用,在API,js中直接使用全局组件

npm方式: npm install -D unplugin-vue-components unplugin-auto-import yarn 方式 : yarn add unplugin-vue-components; yarn add unplugin-auto-import; 使用官方的这个&#xff1a; vite.config.js中配置 plugins: [vue(),AutoImport({resolvers: [ElementPlusResolve…

二十、泛型(2)

本章概要 泛型接口泛型方法 变长参数和泛型方法一个泛型的 Supplier简化元组的使用一个 Set 工具 泛型接口 泛型也可以应用于接口。例如 生成器&#xff0c;这是一种专门负责创建对象的类。实际上&#xff0c;这是 工厂方法 设计模式的一种应用。不过&#xff0c;当使用生成…

muduo源码剖析之SocketOps类

SocketOps 对socket设置API的封装 比较简单,已经编写注释 // Copyright 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file.// Autho…

MapReduce:大数据处理的范式

一、介绍 在当今的数字时代&#xff0c;生成和收集的数据量正以前所未有的速度增长。这种数据的爆炸式增长催生了大数据领域&#xff0c;传统的数据处理方法往往不足。MapReduce是一个编程模型和相关框架&#xff0c;已成为应对大数据处理挑战的强大解决方案。本文探讨了MapRed…

RK3568平台 内存的基本概念

一.Linux的Page Cache page cache&#xff0c;又称pcache&#xff0c;其中文名称为页高速缓冲存储器&#xff0c;简称页高缓。page cache的大小为一页&#xff0c;通常为4K。在linux读写文件时&#xff0c;它用于缓存文件的逻辑内容&#xff0c;从而加快对磁盘上映像和数据的访…

五:ffmpe主要参数的使用

目录 一&#xff1a;回顾一下主要参数 二&#xff1a;使用主要参数操作视频 1、-i 输入流的使用 2、-i 配合 输出流-f使用 三、使用-ss开始时间进行转换 四、使用-t参数&#xff0c;设置转换的时长 一&#xff1a;回顾一下主要参数 -i 设定输入流。 支持本地和网络流 -f …

webpack 的 Loader 和 Plugin 的区别,常见的 loader 和 plugin 有哪些?

结论先行&#xff1a; 1、 Loader 和 Plugin 的区别 Loader 也叫做就是“加载器”&#xff0c;因为 webpack 原生只能解析 js 文件&#xff0c;而对于其他类型文件&#xff0c;则需要借助 loader。所以 loader 的作用就是实现对不同格式文件的解析和处理&#xff0c;例如把 E…

金蝶云星空的网络控制设置

文章目录 金蝶云星空的网络控制设置说明网控参数加入网络控制清除网络控制清除网络控制&#xff08;单个&#xff09;清除网络控制&#xff08;批量&#xff09;清除网络控制&#xff08;批量&#xff0c;参数是拼接好的业务对象&#xff09; 金蝶云星空的网络控制设置 说明 …