在高并发项目中,为了缓解数据库查询压力,通常会引入Redis等非关系型数据库作为缓存。
查询数据的一般步骤为:
step1、查询缓存。
step2、判断是否为空。
如果不为空:
step3、返回查询结果。
如果为空:
step3、查询数据库(数据库没有Redis性能高,通常会有一两秒的延迟,假设2秒)。
step4、更新Redis缓存。
step5、返回查询结果。
在高并发情况下,假设有10个请求顺序进入查询方法,因为查询数据库有一定的时间延迟,导致每个请求都查询不到缓存,容易发生10个请求都查询数据库的情况,这就叫缓存穿透现象。
解决方案如下:
1、抽象出双重检测模板方法
package com.video.cache;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
/**
* 双重检测防止缓存穿透模板方法
* @author 张宇乐
*
*/
@Service
public class CacheTemplate {
@Autowir