在高併發項目中,爲了緩解數據庫查詢壓力,通常會引入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