通过SpringBoot+mybatis+redis项目示例了解了SpringBoot对redis的基本操作,昨天又了解了Redis入门(三)—— 事务
趁着这个势头学习一下怎么在SpringBoot中使用Redis事务。

查阅了网上的资料,主要是两种方法去在SpringBoot中使用Redis事务
通过enableTransactionSupport(亲测无效,原因未知)
使用redisTemplate设置enableTransactionSupport为true,然后开始事务→命令入队→执行事务
private void setDataByTransaction(List<UserBean> userBeans){
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.multi();
userBeans.forEach(item->{
redisTemplate.opsForList().rightPush("redis_user",item);
});
redisTemplate.exec();
}
但是执行事务时出现异常,提醒没有开启的事务

在运行类上加了事务的注解,可惜依旧无效
@SpringBootApplication
@EnableTransactionManagement //开启事务注解
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
研究来研究去,没找到原因,好在这个方法不是推荐的方法,redisTemplate.exec()这个方法并不会去关闭连接。
通过SessionCallback
把所有的操作在同一个 Session 中完成。
private void setDataBySessionCallback(List<UserBean> userBeans){
SessionCallback<List> sessionCallback = new SessionCallback<List>(){
@Override
public <K, V> List execute(RedisOperations<K, V> operations) throws DataAccessException {
operations.multi();
userBeans.forEach(item->{
redisTemplate.opsForList().rightPush("redis_user",item);
});
return redisTemplate.exec();
}
};
}

本文探讨了在SpringBoot项目中使用Redis事务的两种方法:通过enableTransactionSupport(该方法未成功)及通过SessionCallback实现。后者能确保所有操作在一个会话内完成,避免了连接未关闭的问题。
2042

被折叠的 条评论
为什么被折叠?



