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

文章目录

1、缓存穿透

缓存穿透带有恶意性,强调不存在的数据。

2、缓存空对象

3、AlbumInfoApiController --》getAlbumInfo()

java 复制代码
	@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()

java 复制代码
    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

java 复制代码
    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、请求缓存不存在的数据

cpp 复制代码
http://127.0.0.1:8500/api/album/albumInfo/getAlbumInfo/9800


相关推荐
知我Deja_Vu3 天前
redisCommonHelper.generateCode(“GROUP“),Redis 生成码方法
数据库·redis·缓存
Charlie_lll3 天前
Redis脑裂问题处理——基于min-replicas-to-write配置
redis·后端
奇点爆破XC3 天前
Redis迁移
数据库·redis·bootstrap
断手当码农3 天前
Redis 实现分布式锁的三种方式
数据库·redis·分布式
菜鸟小九3 天前
redis原理篇(基本数据结构)
数据结构·数据库·redis
没有bug.的程序员3 天前
电商秒杀系统深度进阶:高并发流量建模、库存零超卖内核与 Redis+MQ 闭环
数据库·redis·缓存·高并发·电商秒杀·流量建模·库存零超卖
菜鸟小九3 天前
redis原理篇(五种数据结构)
数据结构·数据库·redis
初次攀爬者3 天前
Redis分布式锁实现的三种方式-基于setnx,lua脚本和Redisson
redis·分布式·后端
June`3 天前
Redis缓存深度解析:20%数据应对80%请求
数据库·redis
m0_738120723 天前
应急响应——Solar月赛emergency靶场溯源过程(内含靶机下载以及流量分析)
java·开发语言·网络·redis·web安全·系统安全