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

文章目录

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


相关推荐
野犬寒鸦1 小时前
从零起步学习Redis || 第十一章:主从切换时的哨兵机制如何实现及项目实战
java·服务器·数据库·redis·后端·缓存
problc2 小时前
PostgreSQL + Redis + Elasticsearch 实时同步方案实践:从触发器到高性能搜索
redis·elasticsearch·postgresql
yinke小琪3 小时前
从秒杀系统崩溃到支撑千万流量:我的Redis分布式锁踩坑实录
java·redis·后端
会跑的葫芦怪4 小时前
Go语言操作Redis
开发语言·redis·golang
阿湯哥6 小时前
Redis数据库隔离业务缓存对查询性能的影响分析
数据库·redis·缓存
麦兜*6 小时前
Redis 7.2 新特性实战:Client-Side Caching(客户端缓存)如何大幅降低延迟?
数据库·spring boot·redis·spring·spring cloud·缓存·tomcat
he___H8 小时前
尚庭公寓中Redis的使用
数据库·redis·缓存·尚庭公寓
Logintern099 小时前
【学习篇】Redis 分布式锁
redis·分布式·学习
DemonAvenger9 小时前
Redis HyperLogLog 深度解析:从原理到实战,助你优雅解决基数统计问题
数据库·redis·性能优化
matlab的学徒10 小时前
nginx+springboot+redis+mysql+elfk
linux·spring boot·redis·nginx