自学内容网 自学内容网

缓存穿透 问题(缓存空对象)

1、缓存穿透

在这里插入图片描述

2、缓存空对象

在这里插入图片描述

3、AlbumInfoApiController --》getAlbumInfo()

@GetMapping("getAlbumInfo/{albumId}")
public Result<AlbumInfo> getAlbumInfo(@PathVariable("albumId") Long albumId) {
//try {
//Thread.sleep(20);
//} catch (InterruptedException e) {
//throw new RuntimeException(e);
//}
AlbumInfo albumInfo = this.albumInfoService.getAlbumInfo(albumId);
return Result.ok(albumInfo);
}

4、AlbumInfoServiceImpl --》getAlbumInfo()

    public AlbumInfo getAlbumInfo(Long albumId) {

        // 1.先查询缓存,如果命中则直接返回
        AlbumInfo albumInfo = (AlbumInfo) this.redisTemplate.opsForValue().get(RedisConstant.ALBUM_INFO_PREFIX + albumId);
        if (albumInfo != null) {
            return albumInfo;
        }


        // 查询专辑
        albumInfo = this.getById(albumId);
        if (albumInfo != null) {
            // 根据专辑查询专辑标签值
            List<AlbumAttributeValue> albumAttributeValues = this.attributeValueMapper.selectList(new LambdaQueryWrapper<AlbumAttributeValue>().eq(AlbumAttributeValue::getAlbumId, albumId));
            albumInfo.setAlbumAttributeValueVoList(albumAttributeValues);
        }
        // 2.放入缓存
        if (albumInfo == null) {
            // 为了防止缓存穿透:数据即使为空也缓存,只是缓存时间不宜太长。
            this.redisTemplate.opsForValue().set(RedisConstant.ALBUM_INFO_PREFIX + albumId, albumInfo, RedisConstant.ALBUM_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
        }else {
            this.redisTemplate.opsForValue().set(RedisConstant.ALBUM_INFO_PREFIX + albumId, albumInfo, RedisConstant.CACHE_TIMEOUT, TimeUnit.SECONDS);
        }

        return albumInfo;
    }

在这里插入图片描述

5、RedisConstant

    public static final String ALBUM_INFO_PREFIX = "album:info:";
    // 商品如果在数据库中不存在那么会缓存一个空对象进去,但是这个对象是没有用的,所以这个对象的过期时间应该不能太长,
    // 如果太长会占用内存。
    // 定义变量,记录空对象的缓存过期时间
    public static final long ALBUM_TEMPORARY_TIMEOUT = 10 * 60;
    
    public static final long CACHE_TIMEOUT = 24 * 60 * 60;

6、请求缓存不存在的数据

http://127.0.0.1:8500/api/album/albumInfo/getAlbumInfo/9800

在这里插入图片描述
在这里插入图片描述


原文地址:https://blog.csdn.net/m0_65152767/article/details/142369619

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!