缓存解决方案SpringDataRedis

学习目标

  • 掌握SpringDataRedis 的常用操作
  • 能够理解并说出什么是缓存穿透、缓存击穿、缓存雪崩,以及对应的解决方案
  • 使用缓存预热的方式实现商品分类导航缓存
  • 使用缓存预热的方式实现广告轮播图缓存
  • 使用缓存预热的方式实现商品价格缓存

1.SpringDataRedis

1.1 SpringDataRedis简介

SpringDataRedis 属于Spring Data 家族一员,用于对redis的操作进行封装的框架 ,Spring Data : Spring 的一个子项目.Spring 官方提供一套数据层综合解决方案,用 于简化数据库访问,支持NoSQL和关系数据库存储。包括Spring Data JPA 、Spring Data Redis 、SpringDataSolr 、SpringDataElasticsearch 、Spring DataMongodb 等 框架。

1.2 SpringDataRedis入门

1.2.1 准备工作

(1)创建SpringDataRedisDemo工程,在pom.xml中配置相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>com.qingcheng.springdataredis</groupId>
    <artifactId>SpringDataRedisDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
    </dependencies>

</project>

(2)在src/main/resources下创建properties文件redis-config.properties

redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.database=0
redis.maxIdle=300
redis.maxWait=3000

maxIdle :最大空闲数

maxWaitMillis: 连接时的最大等待毫秒数

(3)在src/main/resources下创建applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"      
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  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">
   
   
   <context:property-placeholder location="classpath:redis-config.properties" />
   
   <!-- redis 相关配置 --> 
   <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
     <property name="maxIdle" value="${redis.maxIdle}" />   
     <property name="maxWaitMillis" value="${redis.maxWait}" />  
   </bean>  
  
   <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
       p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>  
   
   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
    	<property name="connectionFactory" ref="jedisConnectionFactory" />
   </bean>


</beans>  

1.2.2 值类型操作

package com.qingcheng.springdataredis.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class TestValue {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 存值 / 修改(当key相同,value不同,把原来覆盖掉)
     */
    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("qingcheng");
    }

    /**
     * 取值
     */
    @Test
    public void getValue(){
        String str = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(str);
    }

    /**
     * 删除
     */
    @Test
    public void deleteValue(){
        Boolean name = redisTemplate.delete("name");
        
    }
}

1.2.3 Set类型操作

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Set;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class TestSet {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void set(){
        redisTemplate.boundSetOps("names").add("曹操");
        redisTemplate.boundSetOps("names").add("刘备");
        redisTemplate.boundSetOps("names").add("孙权");
    }
    @Test
    public void get(){
        //获取所有
        Set names = redisTemplate.boundSetOps("names").members();
        System.out.println(names);
    }

    @Test
    public void deleteValue(){
        Long remove = redisTemplate.boundSetOps("names").remove("曹操");
        System.out.println(remove);
    }

    @Test
    public void deleteAll(){
        Boolean isDelete = redisTemplate.delete("names");
        System.out.println(isDelete);
    }
}

1.2.3 List类型操作

package com.qingcheng.springdataredis.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Set;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class TestList {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 右压栈 (后添加的排在后面)
     *
     */
    @Test
    public void setRightValue(){
        redisTemplate.boundListOps("names").rightPush("刘备");
        redisTemplate.boundListOps("names").rightPush("关羽");
        redisTemplate.boundListOps("names").rightPush("张飞");
    }


    /**
     * 左压栈(后添加的在前面)
     */
    @Test
    public void setLeftValue(){
        redisTemplate.boundListOps("nams_").leftPush("刘备");
        redisTemplate.boundListOps("nams_").leftPush("关羽");
        redisTemplate.boundListOps("nams_").leftPush("张飞");
    }

    /**
     * range(start,end)
     * start:开始位置
     * end 查询多少个 ,如果是"-1" 表示查询所有
     */
    @Test
    public void seachAll(){
        List names = redisTemplate.boundListOps("nams_").range(0, -1);
        System.out.println(names);
    }

    @Test
    public void searchByIndex(){
        Object name = redisTemplate.boundListOps("nams_").index(2);
        System.out.println(name);
    }

    /**
     * 移除集合中某个元素
     * List集合可以重复
     * remove(count,Object) 第一个参数表示移除个数 第二个参数表示移除那个元素
     * 总之就是移除相同元素的个数
     */
    @Test
    public void remove(){
        redisTemplate.boundListOps("nams_").remove(2,"关羽");
    }
    @Test
    public void deleteAll(){
        redisTemplate.delete("nams_");
    }
}

1.2.4 Hash类型操作

类似于Java中的Map

package com.qingcheng.springdataredis.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Set;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class TestHash {
    @Autowired
    private RedisTemplate redisTemplate;

     @Test
    public void setHashValue(){
         redisTemplate.boundHashOps("hashName").put("a","唐僧");
         redisTemplate.boundHashOps("hashName").put("s","孙悟空");
         redisTemplate.boundHashOps("hashName").put("z","猪八戒");
     }

     @Test
    public void getHashKeys(){
         Set keys = redisTemplate.boundHashOps("hashName").keys();
         System.out.println(keys);
     }

     @Test
    public void getHashValues(){
         List values = redisTemplate.boundHashOps("hashName").values();
         System.out.println(values);
     }

    /**
     * 根据key获取value
     */
    @Test
    public void getValueByKey(){
        Object o = redisTemplate.boundHashOps("hashName").get("a");
        System.out.println(o);
    }

    @Test
    public void deleteByKey(){
        redisTemplate.boundHashOps("hashName").delete("a");
    }

    @Test
    public void delete(){
        redisTemplate.delete("hashName");
    }
}

1.2.5 zset类型操作

zset是set的升级版本,它在set的基础上增加了格顺序属性,这属性在添加元素

的同时可以指定,每次指定后,zset会自动重新按照新的值调整顺序。可以理解为有两列 的mysql表,列存储value,列存储分值。

比如主播的人气榜、富豪榜

/*
package com.qingcheng.springdataredis.test;*/
package com.qingcheng.springdataredis.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Set;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml")
public class Testzset {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testSetValue(){
        redisTemplate.boundZSetOps("nameszset").add("曹操",1000);
        redisTemplate.boundZSetOps("nameszset").add("刘备",100);
        redisTemplate.boundZSetOps("nameszset").add("孙权",10);
    }

    /**
     * 默认是由低到高
     */
    @Test
    public void testGetValue(){
        Set nameszset = redisTemplate.boundZSetOps("nameszset").range(0, -1);
        System.out.println(nameszset);
    }

    /**
     * 前两位富豪
     */

    @Test
    public void testTuHaoBang(){
        Set nameszset = redisTemplate.boundZSetOps("nameszset").reverseRange(0, 1);
        System.out.println(nameszset);
    }

    @Test
    public void addScort(){
        redisTemplate.boundZSetOps("nameszset").incrementScore("孙权",200);
    }
    //查询分数和值
    //TypeTuple类型的对象
    @Test
    public void getValueAndScore(){
        Set<ZSetOperations.TypedTuple> nameszset = redisTemplate.boundZSetOps("nameszset").reverseRangeWithScores(0, 9);
        for (ZSetOperations.TypedTuple typedTuple : nameszset) {
            System.out.println(typedTuple.getValue()+"----"+typedTuple.getScore());
        }

    }
}

1.2.6 设置过期时间

    @Test
    public void setTimeOut(){
        //第一个参数表示设置过期的数字
        //第二个参数表示数字的单位, seconds 表示秒
        redisTemplate.boundValueOps("name").expire(10, TimeUnit.SECONDS);
    }

2.缓存穿透、击穿、雪崩

2.1 缓存穿透

缓存穿透是指缓存和数据库中都没有的数据,而用户不断发起请求,如发起为id

为“1”的数据或id为特别大不存在的数据。这时的用户很可能是攻击者,攻击会导致数据 库压力过大。如下面这段代码就存在缓存穿透的问题

public Integer findPrice(Long id) { 
    //从缓存中查询 
    Integer sku_price = (Integer)redisTemplate.boundHashOps("sku_price").get(id); 	     
    if(sku_price==null){ 
        //缓存中没有,从数据库查询 
        Sku sku = skuMapper.selectByPrimaryKey(id); 
       
        if(sku!=null){ 
            //如果数据库有此对象 
            sku_price = sku.getPrice();                       		      
            redisTemplate.boundHashOps("sku_price").put(id,sku_price); 
        } 
    }
    return sku_price; 
}

解决方案:

1.接口层增加校验,如用户鉴权校验,id做基础校验,id<=0的直接拦截;

2.从缓存取不到的数据,在数据库中也没有取到,这时也可以将key-value对写为 key-0。这样可以防止攻击用户反复用同一个id暴力攻击。

代码举例:

public Integer findPrice(Long id) { 
    //从缓存中查询 
    Integer sku_price = (Integer)redisTemplate.boundHashOps("sku_price").get(id); 	     
    if(sku_price==null){ 
        //缓存中没有,从数据库查询 
        Sku sku = skuMapper.selectByPrimaryKey(id); 
        if(sku!=null){ 
            //如果数据库有此对象 
            sku_price = sku.getPrice();                       		      
            redisTemplate.boundHashOps("sku_price").put(id,sku_price); 
        }else{
           redisTemplate.boundHashOps("sku_price").put(id,0);  
        } 
    }
    return sku_price; 
}

  1. 使用缓存预热 ,缓存预热就是将数据提前加入到缓存中,当数据发生变更,再将最新的数据更新到缓

存。后边我们就用缓存预热的方式实现对分类导航、广告轮播图等数据的缓存。

2.2 缓存击穿

缓存击穿是指缓存中没有但数据库中有的数据。这时由于并发用户特别多,同时读

缓存没读到数据,又同时去数据库去取数据,引起数据库压力瞬间增大,造成过大压 力。

以下代码可能会产生缓存击穿:

@Autowired 
private RedisTemplate redisTemplate;
public List<Map> findCategoryTree() {
    //从缓存中查询 
    List<Map> categoryTree= (List<Map>)redisTemplate.boundValueOps("categoryTree").get(); 
    if(categoryTree==null){ 
        Example example=new Example(Category.class); 
        Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("isShow","1");
        //显示 
        List<Category> categories = categoryMapper.selectByExample(example); 
        categoryTree=findByParentId(categories,0); 
        redisTemplate.boundValueOps("categoryTree").set(categoryTree); 
        //过期时间设置 ...... 
    }
    return categoryTree; 
}

主要是缓存过期时间造成的。

解决方案:

1.设置热点数据永远不过期。

2.缓存预热

2.3 缓存雪崩

缓存雪崩是指缓存数据大批量到过期时间,而查询数据量巨大,引起数据库压力过

大甚至down机。和缓存击穿不同的是,缓存击穿指并发查同一条数据缓存雪崩是不同

数据都过期了,很多数据都查不到从而查数据库

解决方案:

1.缓存数据的过期时间设置随机,防止同一时间大量数据过期现象发生。

2.设置热点数据永远不过期。

3.使用缓存预热

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章