Redis缓存的使用极大提升了程序的整体性能和效率,但同时也有一些其他的问题,其中比较典型的问题包括缓存穿透,缓存雪崩,缓存击穿等
什么是缓存穿透
如果前端频繁的发起访问请求,恶意的请求数据库中不存在的key,此时数据库中查询到的数据永远是null,由于null的数据是未存入缓存的,故而每次的访问请求都将会查询数据库,如果此时有恶意攻击,发起洪流式的查询,则很可能会对数据库造成极大的压力,甚至是压垮数据库,这个过程称之为缓存穿透。
缓存穿透的解决方案
目前业界有多种比较成熟的解决方案,其中比较典型的是改造上面所描述的最后一个步骤,把它改为”当查询数据库时候如果没有查询到数据,则将Null返回给前端用户,同时将该Null写入缓存,并且对应的Key设置一定的过期时间,流程结束“,这种方案可以在一定程度上减轻数据库被频繁查询的压力。
实战过程
以商城用户访问某个热点商品为例子,尝试缓存穿透的解决方案。
(1)首先创建数据库,建立数据表,命名为item
CREATE TABLE `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(255) DEFAULT NULL COMMENT '商品编号',
`name` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '商品名称',
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='商品信息表';
INSERT INTO `item` VALUES ('1', 'book_10010', '分布式中间件实战', '2021-07-12 14:21:16');
接着在model模块建立对应的实体类和Mapper
package com.zwx.middleware.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class Item {
private Integer id;
private String code;
private String name;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
}
package com.zwx.middleware.mapper;
import com.zwx.middleware.entity.Item;
import org.apache.ibatis.annotations.Param;
public interface ItemMapper {
//基本增删改查
int deleteByPrimaryKey(Integer id);
int insert(Item record);
int insertSelective(Item record);
Item selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Item record);
int updateByPrimaryKey(Item record);
//根据商品编码查询商品详情
Item selectByCode(@Param("code") String code);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zwx.middleware.mapper.ItemMapper">
<resultMap id="BaseResultMap" type="com.zwx.middleware.entity.Item">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="code" property="code" jdbcType="VARCHAR"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
</resultMap>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">
select
<include refid="Base_Column_List"/>
from item
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from item
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.debug.middleware.model.entity.Item">
insert into item (id, code, name,
create_time)
values (#{id,jdbcType=INTEGER}, #{code,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR},
#{createTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.debug.middleware.model.entity.Item">
insert into item
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="code != null">
code,
</if>
<if test="name != null">
name,
</if>
<if test="createTime != null">
create_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="code != null">
#{code,jdbcType=VARCHAR},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.debug.middleware.model.entity.Item">
update item
<set>
<if test="code != null">
code = #{code,jdbcType=VARCHAR},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.debug.middleware.model.entity.Item">
update item
set code = #{code,jdbcType=VARCHAR},
name = #{name,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
<sql id="Base_Column_List">
id, code, name, create_time
</sql>
<!--根据商品编码查询-->
<select id="selectByCode" resultType="com.debug.middleware.model.entity.Item">
select
<include refid="Base_Column_List"/>
from item
where code = #{code}
</select>
</mapper>
入口启动类加入@MapperScan(“com.zwx.middleware.mapper”)
扫描mapper接口所在的包
创建对应的controller和service
package com.zwx.middleware.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.zwx.middleware.entity.Item;
import com.zwx.middleware.mapper.ItemMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* 缓存穿透service
*/
@Service
@Slf4j
public class CachePassService {
@Resource
private ItemMapper itemMapper;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ObjectMapper objectMapper;
private static final String keyPrefix="item:";
public Item getItemInfo(String itemCode) throws Exception{
Item item=null;
final String key=keyPrefix+itemCode;
ValueOperations valueOperations=redisTemplate.opsForValue();
if (redisTemplate.hasKey(key)){
log.info("---获取商品详情-缓存中存在该商品---商品编号为:{} ",itemCode);
//从缓存中查询该商品详情
Object res=valueOperations.get(key);
if (res!=null && !Strings.isNullOrEmpty(res.toString())){
item=objectMapper.readValue(res.toString(),Item.class);
}
}else{
log.info("---获取商品详情-缓存中不存在该商品-从数据库中查询---商品编号为:{} ",itemCode);
//从数据库中获取该商品详情
item=itemMapper.selectByCode(itemCode);
if (item!=null){
valueOperations.set(key,objectMapper.writeValueAsString(item));
}else{
//过期失效时间TTL设置为30分钟-当然实际情况要根据实际业务决定
valueOperations.set(key,"",30L, TimeUnit.MINUTES);
}
}
return item;
}
}
package com.zwx.middleware.controller.redis;
import com.zwx.middleware.service.CachePassService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* 缓存穿透实战
**/
@RestController
@Slf4j
public class CachePassController {
private static final String prefix="cache/pass";
@Autowired
private CachePassService cachePassService;
/**
* 获取热销商品信息
* @param itemCode
* @return
*/
@GetMapping(prefix+"/item/info")
public Map<String,Object> getItem(@RequestParam String itemCode){
Map<String,Object> resMap=new HashMap<>();
resMap.put("code",0);
resMap.put("msg","成功");
try {
resMap.put("data",cachePassService.getItemInfo(itemCode));
}catch (Exception e){
resMap.put("code",-1);
resMap.put("msg","失败"+e.getMessage());
}
return resMap;
}
}
首先假设获取商品编号为book_10010的书籍信息,地址为http://localhost:8087/middleware/cache/pass/item/info/?itemCode=book_10010
由于是首次查询故而缓存中不存在该商品信息,而是直接从数据库查询获取商品详情信息,结果如图
接着在发起3次同样的请求,可以看到控制台中所有请求都从缓存中查询
最后发起多次商品编号不存在的temCode=book_10012请求
http://localhost:8087/middleware/cache/pass/item/info/?itemCode=book_10012
所以查询数据库结果为Null,然后写入缓存,并设置一定的TTL,下次发起同样的请求的时候直接查询缓存
其他典型的问题介绍
(1)缓存雪崩:指的是在某个时间点,缓存中Key集体过期失效,导致大量查询的数据请求都落到数据库上,使数据库负载过高,压力暴增,设置可能压垮数据库。
这种问题产生的原因主要是大量的Key在某个时间过期失效,所有为了更好的避免这种情况发生,一般的做法使为这些Key设置不同的、随机的TTL,从而错开缓存中Key的失效时间点,可以在某种程度上减轻数据库的查询压力
(2)缓存击穿:指的是缓存中某个频繁访问的key(热点key),在不停的扛着前端的高并发请求,当这个Key突然在某个瞬间失效过期,持续的高并发访问请求就穿破缓存,直接访问数据库,导致数据库压力在某一瞬间暴增,这种现象就像是在一张纸张上凿了一个洞
这种问题的主要原因是还是热点key过期失效了,在实际情况下,既然这个key可以被当做热点频繁访问,那么就该设置这个key永不过期,这样前端的高并发请求几乎永远不会落到数据库上。
总结
不管哪一种问题,其实最终导致的结果几乎都是给数据库造成压力,甚至压垮数据库,他们的解决方案都有一个共性,那就是加强防线,尽量让高并发的请求落在缓存中,避免直接和数据库打交道。