| 知乎专栏 |
例子:设置 name 缓存 10 秒
redisTemplate.opsForValue().set("name","neo",10, TimeUnit.SECONDS);
redisTemplate.opsForValue().get("name")
结果:由于设置的是10秒失效,十秒之内查询有结果,十秒之后返回为null
stringRedisTemplate.opsForValue().set("test", "100"); //向redis里存入数据
stringRedisTemplate.boundValueOps("test").increment(-50); //val做-60操作
stringRedisTemplate.boundValueOps("test").increment(100); //val +100
stringRedisTemplate.opsForValue().get("test") //根据key获取缓存中的val
private void cleanNewToday() {
long begin = System.currentTimeMillis();
redisTemplate.delete("news:today");
long end = System.currentTimeMillis();
logger.info("Schedule clean redis {} 耗时 {} 秒", "cleanNewFlash()", (end-begin) / 1000 );
}
@SneakyThrows
public Optional<Set<String>> anyCache1(String prefix, String key, Supplier<Optional<Set<String>>> supplier) {
// RedisTemplate redisTemplate = new RedisTemplate();
Set<String> value;
if (redisTemplate == null) {
value = supplier.get().get();
this.log("Cache Skip Key: " + key + " Value: " + value);
} else {
String digest = DatatypeConverter.printHexBinary(MessageDigest.getInstance("MD5").digest(key.getBytes(StandardCharsets.UTF_8)));
key = String.format("aigc:%s:%s", prefix, digest);
if (redisTemplate.hasKey(key)) {
value = (Set<String>) redisTemplate.opsForValue().get(key);
this.log("Cache Hit Key: " + key + " Value: " + value);
} else {
value = supplier.get().get();
redisTemplate.opsForValue().set(key, value);
this.log("Cache Set Key: " + key + " Value: " + value);
}
}
return Optional.of(value);
}
@Autowired
private RedisTemplate<String, String> redisTemplate;
Long ttl = redisTemplate.getExpire(String.format("lock:%s", device));
Spring Redis 中设置过期时间方法如下
设置 key
redisTemplate.opsForValue().setIfAbsent("key", "value");
设置过期时间
redisTemplate.expire("key", 30000, TimeUnit.MILLISECONDS);
释放 key
redisTemplate.delete("key");
这样存在一个问题,当程序运行一半被强行终止,可能导致setIfAbsent运行完成,但是expire未被执行,这样 key 便永远不会释放。解决方案如下,使用RedisCallback执行原生 Redis 命令。
String result = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
return commands.set(key, value, "NX", "PX", expire);
}
});