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

news2024/10/6 18:30:36

目录

前言

一、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="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/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/cache
       http://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操作模板,使用该对象可以操作redis
        hibernate课程中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="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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 key
    public static final int NO_PARAM_KEY = 0;
    public static final int NULL_PARAM_KEY = 53;
 
    @Override
    public 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和eqauls
                    key.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 {
    @Autowired
    private ClazzBiz clazzBiz;
 
    @Test
    public 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);

测试类

@Test
    public void test2(){
//        测试 Cacheput 中的 key
        System.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);

测试类

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

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

三、redis击穿、穿透、雪崩

1. 缓存击穿

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

解决方案

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

2. 缓存穿透

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

解决方案

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

3. 缓存雪崩

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

解决方案

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1182750.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【算法设计实验二】分治法解决棋盘覆盖问题

import java.util.*;public class Main {static int cnt0;public static void main(String[] args){Scanner scnew Scanner(System.in);System.out.println("请输入棋盘边长大小&#xff01;");int nsc.nextInt();int[][] gnew int[n][n];System.out.println("请…

word图片的标题跑到了图片的上方。

问题描述&#xff1a;在写论文时&#xff0c;在word文档中插入了一个svg图片&#xff0c;然后在图片下方输入标题。后面可能是调整了svg图片的大小&#xff0c;标题跑到了图片的上方。 具体情况如下图所示。标题明显跑到了图片的上方。 解决办法&#xff1a;把svg图片格式调成…

RTC实时时钟——DS1302

DS1302目录 一、DS1302简介引脚定义与推荐电路 二、芯片手册1.操作寄存器的定义2.时序定义dc1302.cds1302.h 三、蓝桥杯实践 一、DS1302简介 RTC(Real Time Clock):实时时钟&#xff0c;是一种集成电路&#xff0c;通常称为时钟芯片。现在流行的串行时钟电路很多&#xff0c;如…

[java进阶]——方法引用改写Lambda表达式

&#x1f308;键盘敲烂&#xff0c;年薪30万&#x1f308; 目录 &#x1f4d5;概念介绍&#xff1a; ⭐方法引用的前提条件&#xff1a; 1.引用静态方法 2.引用构造方法 ①类的构造&#xff1a; ②数组的构造&#xff1a; 3.引用本类或父类的成员方法 ①本类&#xff1…

深入理解ClickHouse跳数索引

一、跳数索引​ 影响ClickHouse查询性能的因素很多。在大多数场景中&#xff0c;关键因素是ClickHouse在计算查询WHERE子句条件时是否可以使用主键。因此&#xff0c;选择适用于最常见查询模式的主键对于表的设计至关重要。 然而&#xff0c;无论如何仔细地调优主键&#xff…

深度图(Depth Map)

文章目录 深度图深度图是什么深度图的获取方式激光雷达或结构光等传感器的方法激光雷达RGB-D相机 双目或多目相机的视差信息计算深度采用深度学习模型估计深度 深度图的应用场景扩展阅读 深度图 深度图是什么 深度图&#xff08;depth map&#xff09;是一种灰度图像&#xf…

Windows 10 启用 Hyper-V

文章目录 Windows 10 启用 Hyper-V打开控制面板打开任务管理器 Windows 10 启用 Hyper-V 打开控制面板 打开程序和功能 启用或关闭Windows功能 立即重启 打开任务管理器 出现下图&#xff0c;代表已启用

医院pacs系统是什么?

医院pacs系统是什么&#xff1f; PACS系统的概念已从原来将数字化的医学影像通过网络传送到连接在网络上的影像显示工作站上作一般显示和进行数字化存储&#xff0c;发展成为以数字化诊断&#xff08;无纸化、无胶片化&#xff09;为核心的整个影像管理过程&#xff0c;包括&a…

2023/11/7 JAVA学习

ctrl alt t自动重写

Selenium爬取内容并存储至MySQL数据库

前面我通过一篇文章讲述了如何爬取博客摘要等信息。通常,在使用Selenium爬虫爬取数据后,需要存储在TXT文本中,但是这是很难进行数据处理和数据分析的。这篇文章主要讲述通过Selenium爬取我的个人博客信息,然后存储在数据库MySQL中,以便对数据进行分析,比如分析哪个时间段…

MAC设备(M1)环境下编译安装openCV for Java

最近发现一个需求&#xff0c;可以用openCV来实现&#xff0c;碰巧又新买了mac笔记本&#xff0c;就打算利用业余时间安装下openCV。这里将主要步骤记录下&#xff0c;希望能帮助有需要的人。 1、准备编译环境 #查询编译opencv相关依赖 brew info opencv查询结果如下图所示&a…

css排版—— 一篇优雅的文章(中英文) vs 聊天框的特别排版

文章 <div class"contentBox"><p>这是一篇范文——仅供测试使用</p><p>With the coming of national day, I have a one week holiday. I reallyexpect to it, because it want to have a short trip during these days. Iwill travel to Ji…

结合双向LSTM和注意力机制的DQN-CE算法船舶能量调度

Title:Ship Energy Scheduling with DQN-CE Algorithm Combining Bi-directional LSTM and Attention Mechanism 【Applied Energy】结合双向LSTM和注意力机制的DQN-CE算法船舶能量调度(中科院1区Top,IF 11.2) 具体实现方法可以参考原文:论文地址 欢迎大家引用和交流,具体…

如何在在线Excel文档中规范单元格输入

在日常的工作中&#xff0c;我们常常需要处理大量的数据。为了确保数据的准确性和可靠性。我们需要对输入的数据进行规范化和验证。其中一个重要的方面是规范单元格输入。而数据验证作为Excel中一种非常实用的功能&#xff0c;它可以帮助用户规范单元格的输入&#xff0c;从而提…

学习日记01——JS基础01

JavaScrip简单介绍 是前端脚本语音&#xff0c;快速入门js基本语法&#xff0c;本篇文章涉及到JavaScrip基础的变量定义&#xff0c;数据类型和基础的流程控制语句。 使用到的工具 1&#xff0c;vscode 2&#xff0c;chrome浏览器 js的变量定义 准备工作&#xff08;简单的h…

【论文阅读】Progressive Spatio-Temporal Prototype Matching for Text-Video Retrieval

资料链接 论文链接&#xff1a;https://openaccess.thecvf.com/content/ICCV2023/papers/Li_Progressive_Spatio-Temporal_Prototype_Matching_for_Text-Video_Retrieval_ICCV_2023_paper.pdf 代码链接&#xff1a;https://github.com/imccretrieval/prost 背景与动机 文章发…

HTML使用canvas绘制海报(网络图片)

生成前&#xff1a; 生成后&#xff1a; <!DOCTYPE html> <html><head><meta charset"utf-8"><title>媒体参会嘉宾邀请函生成链接</title><link rel"stylesheet" href"https://cdn.jsdelivr.net/npm/vant2.10…

矩阵键盘独立接口设计(Keil+Proteus)

前言 实验&#xff1a;通过4*4的矩阵键盘&#xff0c;按下某个按钮之后会在数码管上面显示对应的键号。&#xff08;0~F&#xff09; 基础操作参考这篇博客&#xff1a; LED数码管的静态显示与动态显示&#xff08;KeilProteus&#xff09;-CSDN博客https://blog.csdn.net/w…

maven 上传本地jar包到nexus

maven上传命令 mvn deploy:deploy-file -DgroupIdcom.microsoft.sqlserver -DartifactIdsqljdbc4 -Dversion4.0 -Dpackagingjar -DfileC:\java\top-sdk-java-1.0.1-lib\lib\bcprov-jdk16-1.46.jar -Durlhttp://ip:port/repository/maven-releases/ -DrepositoryIdsnapshot…

一个Linux自动备份脚本的示例

一个简单的Linux自动备份脚本的示例&#xff0c;根据需要进行自定义&#xff1a; 请确保按照您的需求修改source_dir和backup_dir为要备份的源目录和备份目录的路径。此脚本使用tar命令创建一个以当前日期命名的压缩备份文件&#xff0c;并在备份完成后检查是否成功。此外&…