spring-date-redis版本:1.6.2
场景:在使用setIfAbsent(key,value)
时,想对key设置一个过期时间,同时需要用到setIfAbsent
的返回值来指定之后的流程,所以使用了以下代码:
boolean store = stringRedisTemplate.opsForValue().setIfAbsent(key,value);
if(store){
stringRedisTemplate.expire(key,timeout);
// todo something...
}
这段代码是有问题的:当setIfAbsent成功之后断开连接,下面设置过期时间的代码 stringRedisTemplate.expire(key,timeout);
是无法执行的,这时候就会有大量没有过期时间的数据存在数据库。想到一个办法就是添加事务管理,修改后的代码如下:
stringRedisTemplate.setEnableTransactionSupport(true);
stringRedisTemplate.multi();
boolean store = stringRedisTemplate.opsForValue().setIfAbsent(key,value);
if(store){
stringRedisTemplate.expire(key,timeout);
}
stringRedisTemplate.exec();
if(store){
// todo something...
}
这样就保证了整个流程的一致性。本因为这样就可以了,可是事实总是