spring注解式缓存redis

目录

  • 一、Spring整合redis
    • 1、pom依赖
    • 2、redis.properties
    • 3、spring-redis.xml
    • 4、applicationContext.xml
  • 二、redis注解式缓存
    • 1、**@Cacheable**
      • ①简介
      • ②ClazzBizTest
      • ③ClazzBiz
    • 2、@CachePut
      • ①简介
      • ②ClazzBizTest
      • ③ClazzBiz
    • 3、**@CacheEvict**
      • ①简介
      • ②ClazzBizTest
      • ③ClazzBiz
  • 三、redis击穿穿透雪崩
    • 1、击穿
    • 2、穿透
    • 3、雪崩

一、Spring整合redis

1、pom依赖



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>org.examplegroupId>
  <artifactId>ssm3artifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>ssm3 Maven Webappname>
  
  <url>http://www.example.comurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>

    
    
    <spring.version>5.0.2.RELEASEspring.version>
    
    <mybatis.version>3.4.5mybatis.version>
    
    <mysql.version>5.1.44mysql.version>
    
    <pagehelper.version>5.1.2pagehelper.version>
    
    <mybatis.spring.version>1.3.1mybatis.spring.version>
    
    <commons.dbcp2.version>2.1.1commons.dbcp2.version>
    <commons.pool2.version>2.4.3commons.pool2.version>
    
    <log4j2.version>2.9.1log4j2.version>
    
    <junit.version>4.12junit.version>
    <servlet.version>4.0.0servlet.version>
    <lombok.version>1.18.2lombok.version>

    <ehcache.version>2.10.0ehcache.version>
    <slf4j-api.version>1.7.7slf4j-api.version>

    <redis.version>2.9.0redis.version>
    <redis.spring.version>1.7.1.RELEASEredis.spring.version>
  properties>

  <dependencies>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-ormartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aspectsartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>
    
    <dependency>
      <groupId>com.github.pagehelpergroupId>
      <artifactId>pagehelperartifactId>
      <version>${pagehelper.version}version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>${mybatis.spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-dbcp2artifactId>
      <version>${commons.dbcp2.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-pool2artifactId>
      <version>${commons.pool2.version}version>
    dependency>

    
    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-coreartifactId>
      <version>${log4j2.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-apiartifactId>
      <version>${log4j2.version}version>
    dependency>
    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-webartifactId>
      <version>${log4j2.version}version>
    dependency>

    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>${servlet.version}version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>${lombok.version}version>
      <scope>providedscope>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>javax.servlet.jsp-apiartifactId>
      <version>2.3.3version>
    dependency>
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
    <dependency>
      <groupId>taglibsgroupId>
      <artifactId>standardartifactId>
      <version>1.1.2version>
    dependency>

    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.3version>
    dependency>

    
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-validatorartifactId>
      <version>6.0.7.Finalversion>
    dependency>

    
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.9.3version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-coreartifactId>
      <version>2.9.3version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>2.9.3version>
    dependency>

    
    <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-coreartifactId>
      <version>1.3.2version>
    dependency>

    <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-webartifactId>
      <version>1.3.2version>
    dependency>

    <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-springartifactId>
      <version>1.3.2version>
    dependency>

    <dependency>
      <groupId>net.sf.ehcachegroupId>
      <artifactId>ehcacheartifactId>
      <version>${ehcache.version}version>
    dependency>

    
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j-api.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>jcl-over-slf4jartifactId>
      <version>${slf4j-api.version}version>
      <scope>runtimescope>
    dependency>

    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-slf4j-implartifactId>
      <version>${log4j2.version}version>
    dependency>

    <dependency>
      <groupId>redis.clientsgroupId>
      <artifactId>jedisartifactId>
      <version>${redis.version}version>
    dependency>
    <dependency>
      <groupId>org.springframework.datagroupId>
      <artifactId>spring-data-redisartifactId>
      <version>${redis.spring.version}version>
    dependency>
  dependencies>

  <build>
    <finalName>ssm3finalName>
    <resources>
      
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.xmlinclude>
        includes>
      resource>
      
      <resource>
        <directory>src/main/resourcesdirectory>
        <includes>
          <include>*.propertiesinclude>
          <include>*.xmlinclude>
        includes>
      resource>
    resources>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.pluginsgroupId>
          <artifactId>maven-compiler-pluginartifactId>
          <version>${maven.compiler.plugin.version}version>
          <configuration>
            <source>${maven.compiler.source}source>
            <target>${maven.compiler.target}target>
            <encoding>${project.build.sourceEncoding}encoding>
          configuration>
        plugin>
        <plugin>
          <groupId>org.mybatis.generatorgroupId>
          <artifactId>mybatis-generator-maven-pluginartifactId>
          <version>1.3.2version>
          <dependencies>
            
            <dependency>
              <groupId>mysqlgroupId>
              <artifactId>mysql-connector-javaartifactId>
              <version>${mysql.version}version>
            dependency>
          dependencies>
          <configuration>
            <overwrite>trueoverwrite>
          configuration>
        plugin>
        <plugin>
          <artifactId>maven-clean-pluginartifactId>
          <version>3.1.0version>
        plugin>
        
        <plugin>
          <artifactId>maven-resources-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-compiler-pluginartifactId>
          <version>3.8.0version>
        plugin>
        <plugin>
          <artifactId>maven-surefire-pluginartifactId>
          <version>2.22.1version>
        plugin>
        <plugin>
          <artifactId>maven-war-pluginartifactId>
          <version>3.2.2version>
        plugin>
        <plugin>
          <artifactId>maven-install-pluginartifactId>
          <version>2.5.2version>
        plugin>
        <plugin>
          <artifactId>maven-deploy-pluginartifactId>
          <version>2.8.2version>
        plugin>
      plugins>
    pluginManagement>
  build>
project>

2、redis.properties

redis.hostName=192.168.230.128
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

3、spring-redis.xml


<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">

    
    

    
    <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}"/>
        
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
        
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
        
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
        
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        
        <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
    bean>

    
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          destroy-method="destroy">
        <property name="poolConfig" ref="poolConfig"/>
        
        <property name="hostName" value="${redis.hostName}"/>
        
        <property name="port" value="${redis.port}"/>
        
        <property name="password" value="${redis.password}"/>
        
        <property name="timeout" value="${redis.timeout}"/>
    bean>

    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        
        <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>

    
    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg name="redisOperations" ref="redisTemplate"/>
        
        <property name="defaultExpiration" value="${redis.expiration}"/>
        
        <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>

    
    <bean id="cacheKeyGenerator" class="com.zking.ssm.redis.CacheKeyGenerator">bean>

    
    <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
beans>

4、applicationContext.xml


<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">
    
    <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.propertiesvalue>
                <value>classpath:redis.propertiesvalue>
            list>
        property>
    bean>


    <import resource="applicationContext-mybatis.xml">import>
    <import resource="spring-redis.xml">import>
    <import resource="applicationContext-shiro.xml">import>
beans>

二、redis注解式缓存

1、@Cacheable

①简介

配置在方法或类上,作用:本方法执行后,先去缓存看有没有数据,如果没有,从数据库中查找出来,给缓存中存一份,返回结果,
下次本方法执行,在缓存未过期情况下,先在缓存中查找,有的话直接返回,没有的话从数据库查找
value:缓存位置的一段名称,不能为空
key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL

②ClazzBizTest

package com.zking.shiro;

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;

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

   
}

③ClazzBiz

package com.zking.ssm.biz;

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

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

public interface ClazzBiz {
    @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    int deleteByPrimaryKey(Integer cid);

    int insert(Clazz record);

    int insertSelective(Clazz record);

//    xx=cache-cid:1
//    key的作用改变原有的key生成规则
    @Cacheable(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
//    @CachePut(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
    Clazz selectByPrimaryKey(Integer cid);

    int updateByPrimaryKeySelective(Clazz record);

    int updateByPrimaryKey(Clazz record);

    List<Clazz> listPager(Clazz clazz, PageBean pageBean);
    List<Map> listMapPager(Clazz clazz, PageBean pageBean);
}

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

2、@CachePut

①简介

类似于更新操作,即每次不管缓存中有没有结果,都从数据库查找结果,并将结果更新到缓存,并返回结果
value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存

②ClazzBizTest

同第二点1、②

③ClazzBiz

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

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

3、@CacheEvict

①简介

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

②ClazzBizTest

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

③ClazzBiz

@CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    int deleteByPrimaryKey(Integer cid);

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

三、redis击穿穿透雪崩

1、击穿

高并发量的同时key失效,导致请求直接到达数据库;
设置锁
1.获取 Redis 锁,如果没有获取到,则回到任务队列继续排队
2.获取到锁,从数据库拉取数据并放入缓存中
3.释放锁,其他请求从缓存中拿到数据

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

2、穿透

很多请求都在访问数据库一定不存在的数据,造成请求将缓存和数据库都穿透的情况。
规则排除
可以增加一些参数检验。例如数据库数据 id 一般都是递增的,如果请求 id = -10 这种参数,势必绕过Redis。避免这种情况,可以对用户真实性检验等操作。

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

3、雪崩

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

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

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