这里主要将数据存redis并设置过期时间、通过key删除redis、通过key更新redis(续期)
将数据存redis并设置过期时间
引入redis依赖
import org.springframework.data.redis.core.StringRedisTemplate;
@Autowired
StringRedisTemplate stringRedisTemplate;
@ApiOperation(value = "存redis", notes = "存redis")
@GetMapping("saveRedis")
public RestResponse saveRedis(
) {
String id=IdWorker.generSequeId();
stringRedisTemplate.opsForValue().set("TOKEN:" + id, "object.toString()" + IdWorker.generSequeId(),30L, TimeUnit.SECONDS);
return RestResponse.success(id);
}
@ApiOperation(value = "删除redis", notes = "删除redis")
@GetMapping("delRedis")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "path", name = "token", value = "token", required = true, dataType = "String")
})
public void delRedis(
@RequestParam String token
) {
stringRedisTemplate.delete("TOKEN:" + token);
}
@ApiOperation(value = "更新redis(续期)", notes = "更新redis(续期)")
@GetMapping("updateRedis")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "path", name = "token", value = "token", required = true, dataType = "String")
})
public void updateRedis(
@RequestParam String token
) {
stringRedisTemplate.expire("TOKEN:" + token, 30L, TimeUnit.SECONDS);
}
续期是在原过期时间基础上加上过期时间
内存淘汰策略
Redis中共有下面八种内存淘汰策略:
volatile-lru:设置了过期时间的key使用LRU算法淘汰;
allkeys-lru:所有key使用LRU算法淘汰;
volatile-lfu:设置了过期时间的key使用LFU算法淘汰;
allkeys-lfu:所有key使用LFU算法淘汰;
volatile-random:设置了过期时间的key使用随机淘汰;
allkeys-random:所有key使用随机淘汰;
volatile-ttl:设置了过期时间的key根据过期时间淘汰,越早过期越早淘汰;
noeviction:默认策略,当内存达到设置的最大值时,所有申请内存的操作都会报错(如set,lpush等),只读操作如get命令可以正常执行;
手动配置淘汰策略
打开redis.conf配置文件找到:maxmemory-policy 添加自己需要的淘汰策略
maxmemory-policy noeviction
当然我们也可以使用命令进行修改:
127.0.0.1:6379> config set maxmemory-policy allkeys-Lru
OK
127.0.0.1:6379> config get maxmemory-policy
1) "maxmemory-policy"
2) "allkeys-lru"
过期键的三种删除策略分为:定时删除、惰性删除、定期删除 而Redis使用的是:惰性删除 + 定期删除 文中的《Redis每10秒进行一次过期扫描:》这个属于:定时删除策略(现在Redis6.x应该是不用这种模式)