代码实例一:exec之前获取不到结果值,所有的结果值都是null,exec的时候一起返回结果值
stringRedisTemplate.setEnableTransactionSupport(true);//redis session支持事物
stringRedisTemplate.multi();//开始事物
stringRedisTemplate.opsForValue().set("key1", "value1", Duration.ofDays(1L));
stringRedisTemplate.opsForValue().set("key2", "value2", Duration.ofDays(1L));
stringRedisTemplate.opsForValue().set("key3", "value3", Duration.ofDays(1L));
String string1 = stringRedisTemplate.opsForValue().get("key1");
String string2 = stringRedisTemplate.opsForValue().get("key2");
String string3 = stringRedisTemplate.opsForValue().get("key3");
log.info("string1={},string2={},string3={}", string1, string2, string3);//string1=null,string2=null,string3=null
List<Object> list = stringRedisTemplate.exec();//提交事物list=[true, true, true, value1, value2, value3]
log.info("list={}", list);
代码实例二:exec之前有错误,会放弃所有的命令,做到一起成功、一起失败
log.info("say hello world ...");
List<Object> exec = stringRedisTemplate.execute(new SessionCallback<List<Object>>() {
@Override
public List<Object> execute(RedisOperations operations) throws DataAccessException {
stringRedisTemplate.setEnableTransactionSupport(true);
operations.multi();// 开启事物
operations.opsForValue().set("key1", "value1", Duration.ofDays(1L));
operations.opsForValue().set("key2", "value2", Duration.ofDays(1L));
operations.opsForValue().set("key2", null, Duration.ofDays(1L));//这里有问题
return operations.exec();
}
});
log.info("exec={}", exec);
return exec;
代码实例三:exec中发生错误,不能做到一起成功、一起失败
,成功的就成功了,失败的就失败了
log.info("say hello world ...");
List<Object> exec = stringRedisTemplate.execute(new SessionCallback<List<Object>>() {
@Override
public List<Object> execute(RedisOperations operations) throws DataAccessException {
stringRedisTemplate.setEnableTransactionSupport(true);
operations.multi();// 开启事物
operations.opsForValue().set("key1", "value1", Duration.ofDays(1L));//没问题的就执行了
operations.opsForValue().set("key2", "value2", Duration.ofDays(1L));
operations.opsForSet().add("key1", "aaa", "vvv");//这一行报错了,就不执行了
operations.opsForValue().set("key3", "value3", Duration.ofDays(1L));
return operations.exec();
}
});
log.info("exec={}", exec);
虽然代码会报错抛出异常,但是管道里面的命令,能成功的就已近成功执行了