Springboot 集成 Redis 并判断缓存是否存在以及设置过期时间

warning: 这篇文章距离上次修改已过1082天,其中的内容可能已经有所变动。

Springboot 集成Redis 并判断缓存是否存在以及设置过期时间

    @GetMapping("/api/findbyid")
    public Object findById(int id) {
        String cacheKey = String.valueOf(id);
        //判断缓存是否存在 如果存在则从缓存直接读取 不存在则查库操作
        if (redisTemplate.hasKey(cacheKey)) {
            System.out.println("cache");
        } else {
            System.out.println("sql");
            //redisTemplate.opsForValue().set([CacheKey], [Data], [CacheTimeout], [TimeUnitType]);
            redisTemplate.opsForValue().set(cacheKey, iUserInfo.selectByPrimaryKey(id), 1, TimeUnit.SECONDS);
        }
        return redisTemplate.opsForValue().get(cacheKey);
    }

添加新评论