springboot 事务配置

springboot 事务配置1、全局配置@EnableTransactionManagement@Aspect@ConfigurationpublicclassGlobalTransactionConfig{//写事务的超时时间为10秒privatestaticfinalintTX_METHOD_TIMEOUT=10;//restful包下所有service包或者service的子包的任意类的任意方法privatestaticfinalStringAOP

大家好,又见面了,我是你们的朋友全栈君。

1、全局配置


@EnableTransactionManagement
@Aspect
@Configuration
public class GlobalTransactionConfig {
    //写事务的超时时间为10秒
    private static final int TX_METHOD_TIMEOUT = 10;

    //restful包下所有service包或者service的子包的任意类的任意方法
    private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.jun.cloud.restful..*.service..*.*(..))";

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Bean
    public TransactionInterceptor txAdvice() {

        /**
         * 这里配置只读事务
         */
        RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
        readOnlyTx.setReadOnly(true);
        readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        /**
         * 必须带事务
         * 当前存在事务就使用当前事务,当前不存在事务,就开启一个新的事务
         */
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
        //检查型异常也回滚
        requiredTx.setRollbackRules(
                Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        requiredTx.setTimeout(TX_METHOD_TIMEOUT);

        /***
         * 无事务地执行,挂起任何存在的事务
         */
        RuleBasedTransactionAttribute noTx = new RuleBasedTransactionAttribute();
        noTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);

        Map<String, TransactionAttribute> txMap = new HashMap<>();
        //只读事务
        txMap.put("get*", readOnlyTx);
        txMap.put("query*", readOnlyTx);
        txMap.put("find*", readOnlyTx);
        txMap.put("list*", readOnlyTx);
        txMap.put("count*", readOnlyTx);
        txMap.put("exist*", readOnlyTx);
        txMap.put("search*", readOnlyTx);
        txMap.put("fetch*", readOnlyTx);
        //无事务
        txMap.put("noTx*", noTx);
        //写事务
        txMap.put("add*", requiredTx);
        txMap.put("save*", requiredTx);
        txMap.put("insert*", requiredTx);
        txMap.put("update*", requiredTx);
        txMap.put("modify*", requiredTx);
        txMap.put("delete*", requiredTx);

        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        source.setNameMap(txMap);

        return new TransactionInterceptor(transactionManager, source);
    }

    @Bean
    public Advisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }

}

https://www.cnblogs.com/seasail/p/12179370.html

2、多数据源配置

Spring Boot 使用事务非常简单,首先使用注解 @EnableTransactionManagement 开启事务支持后,然后在访问数据库的Service方法上添加注解 @Transactional 便可。

关于事务管理器,不管是JPA还是JDBC等都实现自接口 PlatformTransactionManager 如果你添加的是 spring-boot-starter-jdbc 依赖,框架会默认注入 DataSourceTransactionManager 实例。如果你添加的是 spring-boot-starter-data-jpa 依赖,框架会默认注入 JpaTransactionManager 实例。

你可以在启动类中添加如下方法,Debug测试,就能知道自动注入的是 PlatformTransactionManager 接口的哪个实现类。

@EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
@SpringBootApplication
public class ProfiledemoApplication {

    @Bean
    public Object testBean(PlatformTransactionManager platformTransactionManager){
        System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());
        return new Object();
    }

    public static void main(String[] args) {
        SpringApplication.run(ProfiledemoApplication.class, args);
    }
}
————————————————
版权声明:本文为CSDN博主「catoop」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/catoop/article/details/50595702

 

这些SpringBoot为我们自动做了,这些对我们并不透明,如果你项目做的比较大,添加的持久化依赖比较多,我们还是会选择人为的指定使用哪个事务管理器。
代码如下:

@EnableTransactionManagement
@SpringBootApplication
public class ProfiledemoApplication {

    // 其中 dataSource 框架会自动为我们注入
    @Bean
    public PlatformTransactionManager txManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public Object testBean(PlatformTransactionManager platformTransactionManager) {
        System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());
        return new Object();
    }

    public static void main(String[] args) {
        SpringApplication.run(ProfiledemoApplication.class, args);
    }
}

在Spring容器中,我们手工注解@Bean 将被优先加载,框架不会重新实例化其他的 PlatformTransactionManager 实现类。

然后在Service中,被 @Transactional 注解的方法,将支持事务。如果注解在类上,则整个类的所有方法都默认支持事务。

对于同一个工程中存在多个事务管理器要怎么处理,请看下面的实例,具体说明请看代码中的注释。
 
 

@EnableTransactionManagement // 开启注解事务管理,等同于xml配置文件中的 <tx:annotation-driven />
@SpringBootApplication
public class ProfiledemoApplication implements TransactionManagementConfigurer {

    @Resource(name="txManager2")
    private PlatformTransactionManager txManager2;

    // 创建事务管理器1
    @Bean(name = "txManager1")
    public PlatformTransactionManager txManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    // 创建事务管理器2
    @Bean(name = "txManager2")
    public PlatformTransactionManager txManager2(EntityManagerFactory factory) {
        return new JpaTransactionManager(factory);
    }

    // 实现接口 TransactionManagementConfigurer 方法,其返回值代表在拥有多个事务管理器的情况下默认使用的事务管理器
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return txManager2;
    }

    public static void main(String[] args) {
        SpringApplication.run(ProfiledemoApplication.class, args);
    }

}

@Component
public class DevSendMessage implements SendMessage {

    // 使用value具体指定使用哪个事务管理器
    @Transactional(value="txManager1")
    @Override
    public void send() {
        System.out.println(">>>>>>>>Dev Send()<<<<<<<<");
        send2();
    }

    // 在存在多个事务管理器的情况下,如果使用value具体指定
    // 则默认使用方法 annotationDrivenTransactionManager() 返回的事务管理器
    @Transactional
    public void send2() {
        System.out.println(">>>>>>>>Dev Send2()<<<<<<<<");
    }

}

注:
如果Spring容器中存在多个 PlatformTransactionManager 实例,并且没有实现接口 TransactionManagementConfigurer 指定默认值,在我们在方法上使用注解 @Transactional 的时候,就必须要用value指定,如果不指定,则会抛出异常。

对于系统需要提供默认事务管理的情况下,实现接口 TransactionManagementConfigurer 指定。

对有的系统,为了避免不必要的问题,在业务中必须要明确指定 @Transactional 的 value 值的情况下。不建议实现接口 TransactionManagementConfigurer,这样控制台会明确抛出异常,开发人员就不会忘记主动指定。
————————————————
版权声明:本文为CSDN博主「catoop」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/catoop/article/details/50595702

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/145145.html原文链接:https://javaforall.net

(0)
上一篇 2022年5月17日 下午11:40
下一篇 2022年5月17日 下午11:40


相关推荐

  • pycharm怎么配置pygame环境—–pycharm怎么配置环境[通俗易懂]

    pycharm怎么配置pygame环境—–pycharm怎么配置环境[通俗易懂]最近学习python要做一个飞机大战的项目,需要配置importpygame新建项目–importpygame,结果是这样滴没有安装这个模块,当然import不了啦,怎么用pycharm下载安装pygame呢?首先选择setting–projectinerpreter,设置项目编译器。大红圈是已经安装过的模块,点击旁边小圈里的小加号是添加新模块,我们轻轻的点一下…

    2022年8月26日
    6
  • matlab产生高斯白噪声

    matlab产生高斯白噪声函数介绍matlab里和随机数有关的函数:(1)rand:产生均值为0.5、幅度在0~1之间的伪随机数。(2)randn:产生均值为0、方差为1的高斯白噪声。(3)randperm(n):产生1到n的均匀分布随机序列。(4)normrnd(a,b,c,d):产生均值为a、方差为b大小为cXd的随机矩阵。rand:返回一个在区间(0,1)内均匀分布的随机数。rand(n):生成0到1之间的n阶(n×n)随机数方阵。rand(m,n):生成0到1之间的m×n的随机数矩阵。

    2025年8月25日
    4
  • 3分钟完成Seedance 2.0插件部署,5个关键环境变量配置错误导致同步失效(附自动检测脚本)

    3分钟完成Seedance 2.0插件部署,5个关键环境变量配置错误导致同步失效(附自动检测脚本)

    2026年3月13日
    2
  • php redis设置过期的键,redis 设置键过期时间[通俗易懂]

    php redis设置过期的键,redis 设置键过期时间[通俗易懂]键过期功能的相关命令设置生存时间:EXPIRE命令和PEXPIRE命令。设置过期时间:EXPIREAT命令和PEXPIREAT命令。查看剩余生存时间:TTL命令和PTTL命令。删除生存时间或过期时间:PERSIST命令。设置生存时间EXPIREkeyseconds将键key的生存时间设置为指定的秒数。PEXPIREkeymilliseconds将键ke…

    2026年4月13日
    2
  • 一篇文章,Vue快速入门!!!

    一篇文章,Vue快速入门!!!①Vue概述及第一个Vue程序(HelloWorld)1.1什么是MVVMMVVM(Model-View-ViewModel)是一种软件设计模式,由微软WPF(用于替代WinForm,以前就是用这个技术开发桌面应用程序的)和Silverlight(类似于JavaApplet,简单点说就是在浏览器上运行WPF)的架构师KenCooper和TedPeters开发,是一种简化用户界面的事件驱动编程方式。由JohnGossman(同样也是WPF和Sliverlight的架构师)与2005年在他的

    2022年5月4日
    55
  • javascript 高级教程 视频_精通JavaScript

    javascript 高级教程 视频_精通JavaScriptJavaScript简介JavaScript历史本节为您讲解JavaScript和客户端脚本的起源。JavaScript实现完整的JavaScript实现是由以下3个不同部分组成的:ECMAScript、文档对象模型、浏览器对象模型。ECMAScript基础ECMAScript语法Java和ECMAScript有一些关键的语法特性相同,也有一…

    2022年8月22日
    10

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号