springboot中redisTemplate事务开启的两种方式

1.开启事务支持,保证在同一个 Connection 中执行命令

redisTemplate.setEnableTransactionSupport(true);

multi与exec介绍:
这2个方法是RedisTemplate.java类提供的事务方法。在使用这个方法之前必须开启事务才能正常使用

@Test
public void testMultiSuccess() {
 // 开启事务支持,在同一个 Connection 中执行命令
 stringRedisTemplate.setEnableTransactionSupport(true);

 stringRedisTemplate.multi();
 stringRedisTemplate.opsForValue().set("name", "qinyi");
 stringRedisTemplate.opsForValue().set("gender", "male");
stringRedisTemplate.opsForValue().set("age", "19");
System.out.println(stringRedisTemplate.exec());     // [true, true, true]
}

2.通过 SessionCallback,保证所有的操作都在同一个 Session 中完成

 SessionCallback<> callback = new SessionCallback<>() 

@Test
@SuppressWarnings(“all”)
public void testSessionCallback() {
SessionCallback callback = new SessionCallback() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
operations.multi();
operations.opsForValue().set(“name”, “qinyi”);
operations.opsForValue().set(“gender”, “male”);
operations.opsForValue().set(“age”, “19”);
return operations.exec();
}
};
总结:我们在 SpringBoot 中操作 Redis 时,使用 RedisTemplate 的默认配置已经能够满足大部分的场景了。如果要执行事务操作,使用 SessionCallback 是比较好,也是比较常用的选择

你可能感兴趣的:(redis)