栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot使用Redis事务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot使用Redis事务

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

查阅了网上的资料,主要是两种方法去在SpringBoot中使用Redis事务

目录
  • 通过enableTransactionSupport(亲测无效,原因未知)
  • 通过SessionCallback

通过enableTransactionSupport(亲测无效,原因未知)

使用redisTemplate设置enableTransactionSupport为true,然后开始事务→命令入队→执行事务

private void setDataByTransaction(List 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 userBeans){
        SessionCallback sessionCallback = new SessionCallback(){
        @Override
        public  List execute(RedisOperations operations) throws DataAccessException {
        operations.multi();
        userBeans.forEach(item->{
        	redisTemplate.opsForList().rightPush("redis_user",item);
       	});
        return redisTemplate.exec();
      }
     };
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/571975.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号