最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何解決Redis緩存穿透(緩存空對象、布隆過濾器)

 更新時間:2024年11月04日 11:43:19   作者:小璐亂撞xllz  
緩存穿透是一個常見的問題,它發(fā)生當(dāng)請求的數(shù)據(jù)既不在緩存中也不在數(shù)據(jù)庫中,文章通過一個查詢商品店鋪的案例,展示了如何結(jié)合這兩種方法來避免緩存穿透,首先利用布隆過濾器過濾掉不存在的id,對于誤判的情況,則采用緩存空對象的策略進(jìn)行補(bǔ)救

背景

緩存穿透是指客戶端請求的數(shù)據(jù)在緩存中和數(shù)據(jù)庫中都不存在,這樣緩存永遠(yuǎn)不會生效,這些請求都會打到數(shù)據(jù)庫

常見的解決方案有兩種,分別是緩存空對象布隆過濾器

1.緩存空對象

優(yōu)點:實現(xiàn)簡單,維護(hù)方便

缺點:額外的內(nèi)存消耗、可能造成短期的不一致

2.布隆過濾器

優(yōu)點:內(nèi)存占用較少,沒有多余key

缺點:實現(xiàn)復(fù)雜、存在誤判可能

代碼實現(xiàn)

前置

這里以根據(jù) id 查詢商品店鋪為案例

實體類

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_shop")
public class Shop implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 主鍵
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    /**
     * 商鋪名稱
     */
    private String name;
    /**
     * 商鋪類型的id
     */
    private Long typeId;
    /**
     * 商鋪圖片,多個圖片以','隔開
     */
    private String images;
    /**
     * 商圈,例如陸家嘴
     */
    private String area;
    /**
     * 地址
     */
    private String address;
    /**
     * 經(jīng)度
     */
    private Double x;
    /**
     * 維度
     */
    private Double y;
    /**
     * 均價,取整數(shù)
     */
    private Long avgPrice;
    /**
     * 銷量
     */
    private Integer sold;
    /**
     * 評論數(shù)量
     */
    private Integer comments;
    /**
     * 評分,1~5分,乘10保存,避免小數(shù)
     */
    private Integer score;
    /**
     * 營業(yè)時間,例如 10:00-22:00
     */
    private String openHours;
    /**
     * 創(chuàng)建時間
     */
    private LocalDateTime createTime;
    /**
     * 更新時間
     */
    private LocalDateTime updateTime;
    @TableField(exist = false)
    private Double distance;
}

常量類

public class RedisConstants {
    public static final Long CACHE_NULL_TTL = 2L;
    public static final Long CACHE_SHOP_TTL = 30L;
    public static final String CACHE_SHOP_KEY = "cache:shop:";
}

工具類

public class ObjectMapUtils {
    // 將對象轉(zhuǎn)為 Map
    public static Map<String, String> obj2Map(Object obj) throws IllegalAccessException {
        Map<String, String> result = new HashMap<>();
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            // 如果為 static 且 final 則跳過
            if (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) {
                continue;
            }
            field.setAccessible(true); // 設(shè)置為可訪問私有字段
            Object fieldValue = field.get(obj);
            if (fieldValue != null) {
                result.put(field.getName(), field.get(obj).toString());
            }
        }
        return result;
    }
    // 將 Map 轉(zhuǎn)為對象
    public static Object map2Obj(Map<Object, Object> map, Class<?> clazz) throws Exception {
        Object obj = clazz.getDeclaredConstructor().newInstance();
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Object fieldName = entry.getKey();
            Object fieldValue = entry.getValue();
            Field field = clazz.getDeclaredField(fieldName.toString());
            field.setAccessible(true); // 設(shè)置為可訪問私有字段
            String fieldValueStr = fieldValue.toString();
            // 根據(jù)字段類型進(jìn)行轉(zhuǎn)換
            if (field.getType().equals(int.class) || field.getType().equals(Integer.class)) {
                field.set(obj, Integer.parseInt(fieldValueStr));
            } else if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) {
                field.set(obj, Boolean.parseBoolean(fieldValueStr));
            } else if (field.getType().equals(double.class) || field.getType().equals(Double.class)) {
                field.set(obj, Double.parseDouble(fieldValueStr));
            } else if (field.getType().equals(long.class) || field.getType().equals(Long.class)) {
                field.set(obj, Long.parseLong(fieldValueStr));
            } else if (field.getType().equals(String.class)) {
                field.set(obj, fieldValueStr);
            } else if(field.getType().equals(LocalDateTime.class)) {
                field.set(obj, LocalDateTime.parse(fieldValueStr));
            }
        }
        return obj;
    }
}

結(jié)果返回類

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    private Boolean success;
    private String errorMsg;
    private Object data;
    private Long total;
    public static Result ok(){
        return new Result(true, null, null, null);
    }
    public static Result ok(Object data){
        return new Result(true, null, data, null);
    }
    public static Result ok(List<?> data, Long total){
        return new Result(true, null, data, total);
    }
    public static Result fail(String errorMsg){
        return new Result(false, errorMsg, null, null);
    }
}

控制層

@RestController
@RequestMapping("/shop")
public class ShopController {
    @Resource
    public IShopService shopService;
    /**
     * 根據(jù)id查詢商鋪信息
     * @param id 商鋪id
     * @return 商鋪詳情數(shù)據(jù)
     */
    @GetMapping("/{id}")
    public Result queryShopById(@PathVariable("id") Long id) {
        return shopService.queryShopById(id);
    }
    /**
     * 新增商鋪信息
     * @param shop 商鋪數(shù)據(jù)
     * @return 商鋪id
     */
    @PostMapping
    public Result saveShop(@RequestBody Shop shop) {
        return shopService.saveShop(shop);
    }
    /**
     * 更新商鋪信息
     * @param shop 商鋪數(shù)據(jù)
     * @return 無
     */
    @PutMapping
    public Result updateShop(@RequestBody Shop shop) {
        return shopService.updateShop(shop);
    }
}

緩存空對象

流程圖為:

服務(wù)層代碼:

public Result queryShopById(Long id) {
    // 從 redis 查詢
    String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
    Map<Object, Object> entries = redisTemplate.opsForHash().entries(shopKey);
    // 緩存命中
    if(!entries.isEmpty()) {
        try {
            // 如果是空對象,表示一定不存在數(shù)據(jù)庫中,直接返回(解決緩存穿透)
            if(entries.containsKey("")) {
                return Result.fail("店鋪不存在");
            }
            // 刷新有效期
            redisTemplate.expire(shopKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            Shop shop = (Shop) ObjectMapUtils.map2Obj(entries, Shop.class);
            return Result.ok(shop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    // 查詢數(shù)據(jù)庫
    Shop shop = this.getById(id);
    if(shop == null) {
        // 存入空值
        redisTemplate.opsForHash().put(shopKey, "", "");
        redisTemplate.expire(shopKey, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
        // 不存在,直接返回
        return Result.fail("店鋪不存在");
    }
    // 存在,寫入 redis
    try {
        redisTemplate.opsForHash().putAll(shopKey, ObjectMapUtils.obj2Map(shop));
        redisTemplate.expire(shopKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    return Result.ok(shop);
}

布隆過濾器

這里選擇使用布隆過濾器存儲存在于數(shù)據(jù)庫中的 id,原因在于,如果存儲了不存在于數(shù)據(jù)庫中的 id,首先由于 id 的取值范圍很大,那么不存在的 id 有很多,因此更占用空間;其次,由于布隆過濾器有一定的誤判率,那么可能導(dǎo)致少數(shù)原本存在于數(shù)據(jù)庫中的 id 被判為了不存在,然后直接返回了,此時就會出現(xiàn)根本性的正確性錯誤。相反,如果存儲的是數(shù)據(jù)庫中存在的 id,那么即使少數(shù)不存在的 id 被判為了存在,由于數(shù)據(jù)庫中確實沒有對應(yīng)的 id,那么也會返回空,最終結(jié)果還是正確的

這里使用 guava 依賴的布隆過濾器

依賴為:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

封裝了布隆過濾器的類(注意初始化時要把數(shù)據(jù)庫中已有的 id 加入布隆過濾器):

public class ShopBloomFilter {
    private BloomFilter<Long> bloomFilter;
    public ShopBloomFilter(ShopMapper shopMapper) {
        // 初始化布隆過濾器,設(shè)計預(yù)計元素數(shù)量為100_0000L,誤差率為1%
        bloomFilter = BloomFilter.create(Funnels.longFunnel(), 100_0000, 0.01);
        // 將數(shù)據(jù)庫中已有的店鋪 id 加入布隆過濾器
        List<Shop> shops = shopMapper.selectList(null);
        for (Shop shop : shops) {
            bloomFilter.put(shop.getId());
        }
    }
    public void add(long id) {
        bloomFilter.put(id);
    }
    public boolean mightContain(long id){
        return bloomFilter.mightContain(id);
    }
}

對應(yīng)的配置類(將其設(shè)置為 bean)

@Configuration
public class BloomConfig {
    @Bean
    public ShopBloomFilter shopBloomFilter(ShopMapper shopMapper) {
        return new ShopBloomFilter(shopMapper);
    }
}

首先要修改查詢方法,在根據(jù) id 查詢時,如果對應(yīng) id 不在布隆過濾器中,則直接返回。然后還要修改保存方法,在保存的時候還需要將對應(yīng)的 id 加入布隆過濾器中

@Override
public Result queryShopById(Long id) {
    // 如果不在布隆過濾器中,直接返回
    if(!shopBloomFilter.mightContain(id)) {
        return Result.fail("店鋪不存在");
    }
    // 從 redis 查詢
    String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
    Map<Object, Object> entries = redisTemplate.opsForHash().entries(shopKey);
    // 緩存命中
    if(!entries.isEmpty()) {
        try {
            // 刷新有效期
            redisTemplate.expire(shopKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            Shop shop = (Shop) ObjectMapUtils.map2Obj(entries, Shop.class);
            return Result.ok(shop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    // 查詢數(shù)據(jù)庫
    Shop shop = this.getById(id);
    if(shop == null) {
        // 不存在,直接返回
        return Result.fail("店鋪不存在");
    }
    // 存在,寫入 redis
    try {
        redisTemplate.opsForHash().putAll(shopKey, ObjectMapUtils.obj2Map(shop));
        redisTemplate.expire(shopKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    return Result.ok(shop);
}
@Override
public Result saveShop(Shop shop) {
    // 寫入數(shù)據(jù)庫
    this.save(shop);
    // 將 id 寫入布隆過濾器
    shopBloomFilter.add(shop.getId());
    // 返回店鋪 id
    return Result.ok(shop.getId());
}

結(jié)合兩種方法

由于布隆過濾器有一定的誤判率,所以這里可以進(jìn)一步優(yōu)化,如果出現(xiàn)誤判情況,即原本不存在于數(shù)據(jù)庫中的 id 被判為了存在,就用緩存空對象的方式將其緩存到 redis 中

@Override
public Result queryShopById(Long id) {
    // 如果不在布隆過濾器中,直接返回
    if(!shopBloomFilter.mightContain(id)) {
        return Result.fail("店鋪不存在");
    }
    // 從 redis 查詢
    String shopKey = RedisConstants.CACHE_SHOP_KEY + id;
    Map<Object, Object> entries = redisTemplate.opsForHash().entries(shopKey);
    // 緩存命中
    if(!entries.isEmpty()) {
        try {
            // 如果是空對象,表示一定不存在數(shù)據(jù)庫中,直接返回(解決緩存穿透)
            if(entries.containsKey("")) {
                return Result.fail("店鋪不存在");
            }
            // 刷新有效期
            redisTemplate.expire(shopKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            Shop shop = (Shop) ObjectMapUtils.map2Obj(entries, Shop.class);
            return Result.ok(shop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    // 查詢數(shù)據(jù)庫
    Shop shop = this.getById(id);
    if(shop == null) {
        // 存入空值
        redisTemplate.opsForHash().put(shopKey, "", "");
        redisTemplate.expire(shopKey, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
        // 不存在,直接返回
        return Result.fail("店鋪不存在");
    }
    // 存在,寫入 redis
    try {
        redisTemplate.opsForHash().putAll(shopKey, ObjectMapUtils.obj2Map(shop));
        redisTemplate.expire(shopKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    return Result.ok(shop);
}

到此這篇關(guān)于解決Redis緩存穿透(緩存空對象、布隆過濾器)的文章就介紹到這了,更多相關(guān)Redis緩存穿透內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Redis常見數(shù)據(jù)類型List列表使用詳解

    Redis常見數(shù)據(jù)類型List列表使用詳解

    Redis的List是一種有序的字符串集合,支持兩端高效插入和刪除,適用于隊列和棧,這篇文章主要介紹了Redis常見數(shù)據(jù)類型List列表使用的相關(guān)資料,需要的朋友可以參考下
    2024-12-12
  • 分布式使用Redis實現(xiàn)數(shù)據(jù)庫對象自增主鍵ID

    分布式使用Redis實現(xiàn)數(shù)據(jù)庫對象自增主鍵ID

    本文介紹在分布式項目中使用Redis生成對象的自增主鍵ID,通過Redis的INCR等命令實現(xiàn)計數(shù)器功能,具有一定的參考價值,感興趣的可以了解一下
    2024-12-12
  • Redis模糊查詢的幾種實現(xiàn)方法

    Redis模糊查詢的幾種實現(xiàn)方法

    本文主要介紹了Redis模糊查詢的幾種實現(xiàn)方法,包括兩種方法KEYS , SCAN,具有一定的參考價值,感興趣的可以了解一下
    2024-02-02
  • redis+lua實現(xiàn)限流的項目實踐

    redis+lua實現(xiàn)限流的項目實踐

    redis有很多限流的算法(比如:令牌桶,計數(shù)器,時間窗口)等,在分布式里面進(jìn)行限流的話,我們則可以使用redis+lua腳本進(jìn)行限流,下面就來介紹一下redis+lua實現(xiàn)限流
    2023-10-10
  • redis由于目標(biāo)計算機(jī)積極拒絕,無法連接的解決

    redis由于目標(biāo)計算機(jī)積極拒絕,無法連接的解決

    這篇文章主要介紹了redis由于目標(biāo)計算機(jī)積極拒絕,無法連接的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Redis實現(xiàn)自動清理過期鍵值對的代碼示例

    Redis實現(xiàn)自動清理過期鍵值對的代碼示例

    在這個數(shù)據(jù)爆炸的時代,內(nèi)存就像珍貴的土地資源,而Redis則是這片土地上的智能管家,它不僅能高效存儲數(shù)據(jù),還能像秋葉定時凋零般,讓鍵值對在指定時間自動消失,本文小編給大家介紹了Redis實現(xiàn)自動清理過期鍵值對實戰(zhàn),需要的朋友可以參考下
    2025-06-06
  • 深入理解Redis7哨兵模式(保姆級教學(xué))

    深入理解Redis7哨兵模式(保姆級教學(xué))

    Redis的主從復(fù)制存在一定的缺陷,為了解決這一問題,Redis官方推薦一種高可用方案哨兵模式,本文主要介紹了深入理解Redis7哨兵模式,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • redis過期回調(diào)功能實現(xiàn)示例

    redis過期回調(diào)功能實現(xiàn)示例

    Redis提供了一種過期回調(diào)的機(jī)制,可以在某個鍵過期時觸發(fā)一個回調(diào)函數(shù),本文就來介紹一下redis過期回調(diào)功能實現(xiàn)示例,感興趣的可以了解一下
    2023-09-09
  • Redis分布式鎖存在的問題(推薦)

    Redis分布式鎖存在的問題(推薦)

    有很多基于Redis實現(xiàn)的分布式鎖方案或者庫,但是有些庫并沒有解決分布式環(huán)境下的一些問題陷阱,這篇文章主要介紹了Redis分布式鎖存在的問題,需要的朋友可以參考下
    2022-12-12
  • Redis中的zset類型詳解

    Redis中的zset類型詳解

    有序集合zset保留了set集合不能有重復(fù)成員的特點,但與set集合不同的是,zset的每個member都有一個唯一的浮點數(shù)類型的分?jǐn)?shù)score與之關(guān)聯(lián),這篇文章主要介紹了Redis的zset類型,需要的朋友可以參考下
    2023-08-08

最新評論

洛阳市| 惠州市| 沐川县| 门头沟区| 蕉岭县| 灵山县| 杂多县| 邮箱| 云和县| 开封市| 淮北市| 怀仁县| 静安区| 正定县| 山丹县| 宁阳县| 太仆寺旗| 伽师县| 壤塘县| 泰宁县| 柏乡县| 府谷县| 勐海县| 彭泽县| 安平县| 乐业县| 凉城县| 册亨县| 乌拉特中旗| 盐亭县| 左权县| 禹州市| 西和县| 福建省| 毕节市| 建平县| 襄城县| 独山县| 江北区| 吴忠市| 勃利县|