SSM之spring注解式缓存redis

目录

一、Spring整合redis

 1.导入相关pom依赖

2. 添加对应的配置文件

3.Spring-redis的整合配置文件

4.测试 

5. 最终的pom依赖

二、reids的注解式开发

 1.第一个注解 @Cacheable

 2.第二个注解 @CachePut

3.第三个注解 @CacheEvict

① @Cacheable 使用注解,缓存并使用

② @CaChePut 只放缓存,不查缓存

③ @CacheEvict 清除缓存,可以去设置权限,清除指定缓存、清除所有缓存

三、redis的击穿穿透雪崩现象及解决方案 ***

四、总结 

1.Spring与redis的整合

2.redis的注解式开发

① 常用的注解

3.reids的击穿穿透血崩 


一、Spring整合redis

 1.导入相关pom依赖

2.9.0
1.7.1.RELEASE


    redis.clients
    jedis
    ${redis.version}


    org.springframework.data
    spring-data-redis
    ${redis.spring.version}

2. 添加对应的配置文件

 redis.properites

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

SSM之spring注解式缓存redis_第1张图片

applicationContext-redis.xml




    
    

    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

    
    
        
        
        
        
        
        
        
        
        
    

    
    
        
        
        
            
        
        
            
        
        
            
        
        
            
        
        
        
    

    
    
        
        
        
        
        
        
        
            
                
            
        
    

    
    

    
    

SSM之spring注解式缓存redis_第2张图片

SSM之spring注解式缓存redis_第3张图片

3.Spring-redis的整合配置文件

        注意1:jdbc.properties与redis.properties文件在整合的时候,会有冲突现象,解决方式,用

                    引入外部多文件方式

        注意2:pom中可以编译的文件及目录

        这里要下载一个插件lombox

package com.zking.ssm.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.util.ClassUtils;

import java.lang.reflect.Array;
import java.lang.reflect.Method;

/**
 * 指定redis中的key value存储中的key字符串的生成规则
 * uname:zs 以前这个uname是手动赋予的
 * 这个uname不想手写了,就通过它来写
 *
 * @enableCache 这个key就通过它来做的
 */

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

    @Cacheable
    @Override
    public Object generate(Object target, Method method, Object... params) {
        StringBuilder key = new StringBuilder();
//        com.zking.service.ClzServie.get:1
        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;
    }
}

SSM之spring注解式缓存redis_第4张图片

这时我们运行就会出错。 

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



    
    
        
        
        
            
                classpath:jdbc.properties
                classpath:redis.properties
            
        
    

    
    
    
    
    
    

SSM之spring注解式缓存redis_第5张图片

4.测试 

能运行起来就说明Spring整合redis没有问题了 

SSM之spring注解式缓存redis_第6张图片

SSM之spring注解式缓存redis_第7张图片

5. 最终的pom依赖




  4.0.0

  org.example
  ssm2
  1.0-SNAPSHOT
  war

  ssm2 Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.8
    1.8
    3.7.0

    
    
    5.0.2.RELEASE
    
    3.4.5
    
    5.1.44
    
    5.1.2
    
    1.3.1
    
    2.1.1
    2.4.3
    
    2.9.1
    
    4.12
    4.0.0
    1.18.2

    2.9.0
    1.7.1.RELEASE
  

  
    
    
      org.springframework
      spring-context
      ${spring.version}
    
    
      org.springframework
      spring-orm
      ${spring.version}
    
    
      org.springframework
      spring-tx
      ${spring.version}
    
    
      org.springframework
      spring-aspects
      ${spring.version}
    
    
      org.springframework
      spring-web
      ${spring.version}
    
    
      org.springframework
      spring-test
      ${spring.version}
    

    
    
      org.mybatis
      mybatis
      ${mybatis.version}
    
    
    
      mysql
      mysql-connector-java
      ${mysql.version}
    
    
    
      com.github.pagehelper
      pagehelper
      ${pagehelper.version}
    
    
    
      org.mybatis
      mybatis-spring
      ${mybatis.spring.version}
    

    
    
      org.apache.commons
      commons-dbcp2
      ${commons.dbcp2.version}
    
    
      org.apache.commons
      commons-pool2
      ${commons.pool2.version}
    

    
    
    
      org.apache.logging.log4j
      log4j-core
      ${log4j2.version}
    
    
      org.apache.logging.log4j
      log4j-api
      ${log4j2.version}
    
    
    
      org.apache.logging.log4j
      log4j-web
      ${log4j2.version}
    

    
    
      junit
      junit
      ${junit.version}
      test
    
    
      javax.servlet
      javax.servlet-api
      ${servlet.version}
      provided
    
    
      org.projectlombok
      lombok
      ${lombok.version}
      provided
    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    
    
    
      javax.servlet.jsp
      javax.servlet.jsp-api
      2.3.3
    
    
      jstl
      jstl
      1.2
    
    
      taglibs
      standard
      1.1.2
    

    
      commons-fileupload
      commons-fileupload
      1.3.3
    

    
    
      org.hibernate
      hibernate-validator
      6.0.7.Final
    


    
      com.fasterxml.jackson.core
      jackson-databind
      2.9.3
    
    
      com.fasterxml.jackson.core
      jackson-core
      2.9.3
    
    
      com.fasterxml.jackson.core
      jackson-annotations
      2.9.3
    



    
      redis.clients
      jedis
      ${redis.version}
    
    
      org.springframework.data
      spring-data-redis
      ${redis.spring.version}
    
  

  
    ssm2
    
      
      
        src/main/java
        
          **/*.xml
        
      
      
      
        src/main/resources
        
          *.properties
          *.xml
        
      
    
    
      
        
          org.apache.maven.plugins
          maven-compiler-plugin
          ${maven.compiler.plugin.version}
          
            ${maven.compiler.source}
            ${maven.compiler.target}
            ${project.build.sourceEncoding}
          
        
        
          org.mybatis.generator
          mybatis-generator-maven-plugin
          1.3.2
          
            
            
              mysql
              mysql-connector-java
              ${mysql.version}
            
          
          
            true
          
        
        
          maven-clean-plugin
          3.1.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-war-plugin
          3.2.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  

二、reids的注解式开发

启动我们的虚拟机电脑,开启连接工具,启动服务6379

SSM之spring注解式缓存redis_第8张图片

 1.第一个注解 @Cacheable

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

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

这个读的就是Spring上下文 

 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})

package com.zking.ssm.redis;

import com.zking.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;

/**
 * @author 敢敢
 * @site www.javajwj.com
 * @company xxx公司
 * @create  2022-10-27 17:00
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class ClazzBizTest {
    @Autowired
    private ClazzBiz clazzBiz;

    @Test
    public void test1(){
        System.out.println(clazzBiz.selectByPrimaryKey(1));
        System.out.println(clazzBiz.selectByPrimaryKey(1));
    }
}

效果图:SQL语句执行了两次,没有用到缓存 

SSM之spring注解式缓存redis_第9张图片

 此时的ClazzBiz

package com.zking.ssm.biz;

import com.zking.ssm.model.Clazz;
import com.zking.ssm.util.PageBean;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;
import java.util.Map;

public interface ClazzBiz {
    int deleteByPrimaryKey(Integer cid);

    int insert(Clazz record);

    int insertSelective(Clazz record);

    Clazz selectByPrimaryKey(Integer cid);

    int updateByPrimaryKeySelective(Clazz record);

    int updateByPrimaryKey(Clazz record);

    List listPager(Clazz clazz, PageBean pageBean);

    List listMapPager(Clazz clazz, PageBean pageBean);
}

修改里面ClazzBiz添加一个注释

    @Cacheable(value = "xx")
    Clazz selectByPrimaryKey(Integer cid);

效果:当我们在来查询的时候,它就不会在走数据库了,全部走缓存,数据从缓存里拿

SSM之spring注解式缓存redis_第10张图片

 此时redis桌面管理器

SSM之spring注解式缓存redis_第11张图片

当我们在次去执行的时候,它就不会走数据库了,全部走缓存,走缓存的话一次都不查询了。

SSM之spring注解式缓存redis_第12张图片

再次修改注释里面的属性 key改变原有的key生成规则

//    xx=cache-cid:1
//    key的作用是改变原有的key生成规则
    @Cacheable(value = "xx",key = "'cid:'+#cid")
    Clazz selectByPrimaryKey(Integer cid);
 @Test
    public void test1(){
        System.out.println(clazzBiz.selectByPrimaryKey(2));
        System.out.println(clazzBiz.selectByPrimaryKey(2));
    }

SSM之spring注解式缓存redis_第13张图片

再次修改注释里的属性 condition判断什么时候修改key属性 将库清空

SSM之spring注解式缓存redis_第14张图片

//    xx=cache-cid:1
//    key的作用是改变原有的key生成规则
//    改变它的生成规则,只有key大于6的时候生成缓存,key小于6不生成缓存
    @Cacheable(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
    Clazz selectByPrimaryKey(Integer cid);
  @Test
    public void test1(){
        System.out.println(clazzBiz.selectByPrimaryKey(3));
        System.out.println(clazzBiz.selectByPrimaryKey(3));
    }

效果如图所示:查了两次数据库 

SSM之spring注解式缓存redis_第15张图片

我们修改ClazzBizTest.java

 @Test
    public void test1(){
        System.out.println(clazzBiz.selectByPrimaryKey(8));
        System.out.println(clazzBiz.selectByPrimaryKey(8));
    }

结果肯定查询了一次数据库,还生成了缓存

SSM之spring注解式缓存redis_第16张图片

 2.第二个注解 @CachePut

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

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

ClazzBiz.java

 @CachePut(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
    Clazz selectByPrimaryKey(Integer cid);

ClazzBizTest.java

@Test
    public void test1(){
        System.out.println(clazzBiz.selectByPrimaryKey(9));
        System.out.println(clazzBiz.selectByPrimaryKey(9));
    }

 效果如图所示:它唯一的区别就是放缓存,而不负责存缓存

SSM之spring注解式缓存redis_第17张图片

3.第三个注解 @CacheEvict

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

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

    @CacheEvict(value = "xx",key = "'cid:'+#cid")
    int deleteByPrimaryKey(Integer cid);
@Test
    public void test2(){
        clazzBiz.deleteByPrimaryKey(9);
    }

@CacheEvict:把指定的数据清空的同时,清除掉redis桌面管理器这里面的缓存
清空某一条数据,你传的id是什么,就把id对应的缓存给清掉。 

效果如图所示:id为9的清除掉了 

 SSM之spring注解式缓存redis_第18张图片

ClazzBizImpl.java 

 @Override
    public int deleteByPrimaryKey(Integer cid) {

//        return clazzMapper.deleteByPrimaryKey(cid);
        System.out.println("不做任何操作,因为我们只清除缓存,不清除数据库");
        return 0;
    }

ClazzBizTest.java

@Test
    public void test2(){
        clazzBiz.deleteByPrimaryKey(10);
    }

效果如图所示:

SSM之spring注解式缓存redis_第19张图片

我们在把id为10的数据加入到缓存中.

SSM之spring注解式缓存redis_第20张图片 

ClazzBiz.java

//清除所有allEntries缓存,以xx开头的
    @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    int deleteByPrimaryKey(Integer cid);

运行结果如图所示:

SSM之spring注解式缓存redis_第21张图片 

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

① @Cacheable 使用注解,缓存并使用

② @CaChePut 只放缓存,不查缓存

③ @CacheEvict 清除缓存,可以去设置权限,清除指定缓存、清除所有缓存

三、redis的击穿穿透雪崩现象及解决方案 ***

关于redis的击穿穿透雪崩的网址:Redis-击穿、穿透、雪崩 - 知乎  

 击穿:高并发量的同时key失效,导致请求直接到达数据库;

 设置锁
1.获取 Redis 锁,如果没有获取到,则回到任务队列继续排队
2.获取到锁,从数据库拉取数据并放入缓存中
3.释放锁,其他请求从缓存中拿到数据

限流:请求redis之前做流量削峰

 穿透: 很多请求都在访问数据库一定不存在的数据,造成请求将缓存和数据库都穿透的情况。

规则排除
可以增加一些参数检验。例如数据库数据 id 一般都是递增的,如果请求 id = -10 这种参数,势必绕过Redis。避免这种情况,可以对用户真实性检验等操作。

null值填充
当缓存穿透时,redis存入一个类似null的值,下次访问则直接缓存返回空,当数据库中存在该数据的值则需要把redis存在的null值清除并载入新值,此方案不能解决频繁随机不规则的key请求。

 雪崩: 雪崩和击穿类似,不同的是击穿是一个热点 Key 某时刻失效,而雪崩是大量的热点 Key 在一瞬间失效 。

给不同的热点key设置不同的缓存策略

图形解释:SSM之spring注解式缓存redis_第22张图片

击穿、穿透、血崩它们都有共同点会有大量请求:通用的解决方案限流,限流用到的技术RabbitMQ,流量血崩
击穿的解决方案:给redis上锁,第一个请求拿到锁,从数据库拿数据,缓存到redis中,

                            然后在把锁释放,后面的请求就可以访问了
穿透:因为它的现象是反而不存在的数据,redis跟MySQL都没有这条数据但此时我们可以在

          redis设置一条压根就不存在的数据,那下次在访问的话,

           那么redis就有数据请求就不会到达MySQL,这是关于穿透
血崩:是因为大量的key同一时间发生变化,那我们可以采用disregard的方式,
              给不同的key设置不同的缓存策略,设置不同的存活时间

四、总结 

1.Spring与redis的整合

① pom依赖

        reids/spring-redis

② redis.properties

③ spring-redis.xml

        reids.properties/jedispool/connextfactory 

        注1:redis.properties和jdbc.properties的冲突

                外部多文件引入的方式

        注2:pom.xml设置 所有 properties文件都会编译进target文件夹

④ ssm项目能够启动

2.redis的注解式开发

 缓存头-cache-chachekeygenenater

① 常用的注解

@cacheable

        属性:

                key:存储在redis服务中的键

                value:存储数据所在的值

                condition:符合某些条件才会使用到缓存

        作用:一次读取的数据存入缓存,本次读取数据就在缓存取,而不会走数据库

@cacheput

        属性: 

                key:存储在redis服务中的键

                value:存储数据所在的值

                condition:符合某些条件才会使用到缓存

        作用:只写不读 

@cacheenvict

        作用:人为的清除缓存

3.reids的击穿穿透血崩 

击穿:一瞬间大量请求访问某一个key的数据,而这个key正好失效;那么此时大量请求会到数据库

方案:限流,设置redis锁 

穿透:访问一个redis以及数据库压根不存在的数据,每一次请求都会到达数据库

方案:设置“null”值

血崩:一瞬间大量请求访问多个key的数据,而多个key同时失效

方案:通过定时任务,设置不同的缓存机制

你可能感兴趣的:(redis,spring,缓存)