添加Redis缓存

本文介绍了如何在SpringBoot项目中使用Redis进行缓存查询,包括优先查询Redis、缓存更新设置有效期、处理缓存穿透问题(如空对象和布隆过滤)以及应对缓存雪崩的解决方案。
摘要由CSDN通过智能技术生成

1.缓存查询

在这里插入图片描述
在service层Impl文件中,进行查询时优先向Redis中查数据,查到就查到了,没有查到向mysql数据库中查,查到之后不先返回,而是先将数据存到数据库(缓存),在再返回数据。

1.1 代码实现(缓存使用字符串)

controller层正常调用service层中的接口,在Impl中

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);//将JSON转成制定类型对象
            return Result.ok(shop);
        }
        Shop shop = getById(id);
        if (shop == null){
            return Result.fail("不存在");
        }
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop));//将对象转成json
        return Result.ok(shop);
    }
}

2.缓存更新

在缓存的时候添加有效期

stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
	@Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("Id不可以为空");
        }
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();

    }

3.缓存穿透

缓存穿透 :缓存穿透是指客户端请求的数据在缓存中和数据库中都不存在,这样缓存永远不会生效,这些请求都会打到数据库。
常见的解决方案有两种:

  • 缓存空对象
    • 优点:实现简单,维护方便
    • 缺点:
      • 额外的内存消耗
      • 可能造成短期的不一致
  • 布隆过滤
    • 优点:内存占用较少,没有多余key
    • 缺点:
      • 实现复杂
      • 存在误判可能

编码解决商品查询的缓存穿透问题:
在这里插入图片描述

@Override
    public Result queryById(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1.从redis查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在 blank(空白字符(空格字符,制表符,换行符))
        if (StrUtil.isNotBlank(shopJson)){
            //3.存在直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //4.判断是否为空
        if (shopJson != null){
            return Result.fail("不存在");
        }
        //5.向数据库查询
        Shop shop = getById(id);
        if (shop == null){
            //数据库不存在,向redis存入null值,存活时间弄短一些
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return Result.fail("不存在");
        }
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

缓存雪崩问题及解决思路

缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机,导致大量请求到达数据库,带来巨大压力。
解决方案:

  • 给不同的Key的TTL添加随机值
  • 利用Redis集群提高服务的可用性
  • 给缓存业务添加降级限流策略
  • 给业务添加多级缓存
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个可能的实现示例,供参考。 1. DAO层及Mapper,这里使用MyBatis框架进行数据库访问,假设中奖记录的表名为`lottery`: ```java @Mapper public interface LotteryMapper { @Select("SELECT COUNT(*) FROM lottery WHERE DATE(create_time) BETWEEN #{startDate} AND #{endDate}") int countByCreateTime(@Param("startDate") Date startDate, @Param("endDate") Date endDate); } ``` 2. Service层,统计逻辑可以在这里编写,同时使用Redis缓存中间结果: ```java @Service public class TrendService { private final LotteryMapper lotteryMapper; private final RedisTemplate<String, Object> redisTemplate; public TrendService(LotteryMapper lotteryMapper, RedisTemplate<String, Object> redisTemplate) { this.lotteryMapper = lotteryMapper; this.redisTemplate = redisTemplate; } public List<Integer> getTrend() { String key = "trend"; List<Integer> trend = (List<Integer>) redisTemplate.opsForValue().get(key); if (trend != null) { return trend; } LocalDateTime now = LocalDateTime.now(); LocalDateTime weekStart = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)); LocalDateTime monthStart = now.withDayOfMonth(1); LocalDateTime yearStart = now.withDayOfYear(1); Date start = Date.from(yearStart.atZone(ZoneId.systemDefault()).toInstant()); Date end = Date.from(now.atZone(ZoneId.systemDefault()).toInstant()); int weekCount = lotteryMapper.countByCreateTime(Date.from(weekStart.atZone(ZoneId.systemDefault()).toInstant()), end); int monthCount = lotteryMapper.countByCreateTime(Date.from(monthStart.atZone(ZoneId.systemDefault()).toInstant()), end); int yearCount = lotteryMapper.countByCreateTime(start, end); trend = Arrays.asList(weekCount, monthCount, yearCount); redisTemplate.opsForValue().set(key, trend); redisTemplate.expire(key, 10, TimeUnit.MINUTES); return trend; } } ``` 3. Controller层,将请求映射到Service方法,并返回统计结果: ```java @RestController public class TrendController { private final TrendService trendService; public TrendController(TrendService trendService) { this.trendService = trendService; } @GetMapping("/trend") public List<Integer> getTrend() { return trendService.getTrend(); } } ``` 需要注意的是,这只是一个简单的示例,具体的实现方式还需要根据您的具体需求进行调整。同时,为了使示例尽可能简单,这里未进行异常处理、日志记录等其他常规操作,实际使用时需要添加相应的处理逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值