百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Spring框架中的两大事务管理神器:声明式与编程式

ccwgpt 2025-03-24 14:22 21 浏览 0 评论

前言

在企业级应用开发中,事务管理是保障数据一致性与完整性的关键环节。Spring Boot 为我们提供了强大的事务管理支持,主要包括声明式事务和编程式事务两种方式。当涉及到多数据源的场景时,结合MyBatis-Plus框架,事务管理变得更加复杂但也更具灵活性。

本文将深入探讨如何在Spring Boot + MyBatis-Plus多数据源环境下实现这两种事务管理方式。

一、多数据源配置

首先,我们需要配置多个数据源。假设我们有两个数据源,分别为dataSource1和dataSource2。

1. 引入依赖


    
    
        org.springframework.boot
        spring-boot-starter-jdbc
    
    
    
        com.baomidou
        mybatis-plus-boot-starter
        最新版本
    
    
    
        mysql
        mysql-connector-java
    

2. 配置数据源

在application.yml文件中配置两个数据源的连接信息。

spring:
  datasource:
    primary:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
      username: root
      password: root
    secondary:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
      username: root
      password: root

3. 配置数据源 Bean

创建配置类,定义两个数据源的 Bean。

@Configuration
public class DataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

4. 配置 MyBatis-Plus

为每个数据源配置对应的MyBatis-Plus的SqlSessionFactory和MapperScannerConfigurer。

@Configuration
@MapperScan(basePackages = "com.example.demo.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryMyBatisPlusConfig {

    @Bean
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        bean.setConfiguration(configuration);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/primary/*.xml"));
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setBanner(false);
        bean.setGlobalConfig(globalConfig);
        return bean.getObject();
    }

    @Bean
    @Primary
    public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /***
     * sqlSessionTemplate与Spring事务管理一起使用,可以确保实际使用的 SqlSession 是与当前的 Spring 事务相关联的。这样,会话的生命周期(包括根据 Spring 的事务配置,在必要时关闭、提交或回滚会话)将由 Spring 管理
     */
    @Bean
    @Primary
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

@Configuration
@MapperScan(basePackages = "com.example.demo.mapper.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryMyBatisPlusConfig {

    @Bean
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        bean.setConfiguration(configuration);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/secondary/*.xml"));
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setBanner(false);
        bean.setGlobalConfig(globalConfig);
        return bean.getObject();
    }

    @Bean
    public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

二、声明式事务在多数据源下的实现

在多数据源场景下使用声明式事务,需要注意事务管理器的选择。

1. 启用声明式事务

和单数据源一样,在主应用类上添加@EnableTransactionManagement注解。

@SpringBootApplication
@EnableTransactionManagement
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

2. 使用注解配置事务

在需要事务管理的方法或类上使用@Transactional注解,并指定事务管理器。

@Service
public class UserService {

    @Transactional(value = "primaryTransactionManager", rollbackFor = Exception.class)
    public void createUser(User user) {
        // 使用primaryDataSource对应的Mapper进行数据库操作
    }

    @Transactional(value = "secondaryTransactionManager", rollbackFor = Exception.class)
    public void updateUser(User user) {
        // 使用secondaryDataSource对应的Mapper进行数据库操作
    }
}

在上述代码中,createUser方法使用primaryTransactionManager事务管理器,确保对primaryDataSource数据源的操作在一个事务中;updateUser方法使用secondaryTransactionManager事务管理器,管理对secondaryDataSource数据源的操作。

3. 事务传播行为

在多数据源场景下,事务传播行为同样适用。例如,如果一个方法调用另一个跨数据源的事务方法,需要合理配置事务传播行为以确保数据的一致性。

@Transactional(value = "primaryTransactionManager", propagation = Propagation.REQUIRES_NEW)
public void complexOperation() {
    // 调用另一个数据源的事务方法
    userService.updateUser(new User());
}

三、编程式事务在多数据源下的实现

编程式事务在多数据源场景下,可以精确控制每个数据源的事务边界。

1. 使用 TransactionTemplate

为每个数据源配置对应的TransactionTemplate。

@Configuration
public class TransactionConfig {

    @Bean
    public TransactionTemplate primaryTransactionTemplate(@Qualifier("primaryTransactionManager") PlatformTransactionManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }

    @Bean
    public TransactionTemplate secondaryTransactionTemplate(@Qualifier("secondaryTransactionManager") PlatformTransactionManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }
}

然后在服务类中使用对应的TransactionTemplate执行事务操作。

@Service
public class ProductService {

    @Autowired
    @Qualifier("primaryTransactionTemplate")
    private TransactionTemplate primaryTransactionTemplate;

    @Autowired
    @Qualifier("secondaryTransactionTemplate")
    private TransactionTemplate secondaryTransactionTemplate;

    public void updateProductInPrimary(Product product) {
        primaryTransactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                try {
                    // 使用primaryDataSource对应的Mapper进行数据库操作
                    return null;
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    public void updateProductInSecondary(Product product) {
        secondaryTransactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                try {
                    // 使用secondaryDataSource对应的Mapper进行数据库操作
                    return null;
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }
}

2. 使用 TransactionManager

直接使用PlatformTransactionManager也可以实现编程式事务控制。

@Service
public class OrderService {

    @Autowired
    @Qualifier("primaryTransactionManager")
    private PlatformTransactionManager primaryTransactionManager;

    @Autowired
    @Qualifier("secondaryTransactionManager")
    private PlatformTransactionManager secondaryTransactionManager;

    public void placeOrderInPrimary(Order order) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = primaryTransactionManager.getTransaction(def);
        try {
            // 使用primaryDataSource对应的Mapper进行数据库操作
            primaryTransactionManager.commit(status);
        } catch (Exception e) {
            primaryTransactionManager.rollback(status);
            throw e;
        }
    }

    public void placeOrderInSecondary(Order order) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = secondaryTransactionManager.getTransaction(def);
        try {
            // 使用secondaryDataSource对应的Mapper进行数据库操作
            secondaryTransactionManager.commit(status);
        } catch (Exception e) {
            secondaryTransactionManager.rollback(status);
            throw e;
        }
    }
}

四、总结

在 Spring Boot + MyBatis-Plus 多数据源的环境中,无论是声明式事务还是编程式事务,都需要我们仔细配置和管理事务管理器,以确保不同数据源的操作能够在正确的事务控制下进行。声明式事务通过注解简化了事务配置,适用于大多数常规业务场景;而编程式事务则提供了更灵活、更精细的事务控制,适用于复杂的业务逻辑。通过合理运用这两种事务管理方式,我们能够构建出数据一致性高、稳定性强的企业级应用程序。在实际开发过程中,需要根据具体的业务需求和数据操作特点,选择最合适的事务管理策略。

相关推荐

十分钟让你学会LNMP架构负载均衡(impala负载均衡)

业务架构、应用架构、数据架构和技术架构一、几个基本概念1、pv值pv值(pageviews):页面的浏览量概念:一个网站的所有页面,在一天内,被浏览的总次数。(大型网站通常是上千万的级别)2、u...

AGV仓储机器人调度系统架构(agv物流机器人)

系统架构层次划分采用分层模块化设计,分为以下五层:1.1用户接口层功能:提供人机交互界面(Web/桌面端),支持任务下发、实时监控、数据可视化和报警管理。模块:任务管理面板:接收订单(如拣货、...

远程热部署在美团的落地实践(远程热点是什么意思)

Sonic是美团内部研发设计的一款用于热部署的IDEA插件,本文其实现原理及落地的一些技术细节。在阅读本文之前,建议大家先熟悉一下Spring源码、SpringMVC源码、SpringBoot...

springboot搭建xxl-job(分布式任务调度系统)

一、部署xxl-job服务端下载xxl-job源码:https://gitee.com/xuxueli0323/xxl-job二、导入项目、创建xxl_job数据库、修改配置文件为自己的数据库三、启动...

大模型:使用vLLM和Ray分布式部署推理应用

一、vLLM:面向大模型的高效推理框架1.核心特点专为推理优化:专注于大模型(如GPT-3、LLaMA)的高吞吐量、低延迟推理。关键技术:PagedAttention:类似操作系统内存分页管理,将K...

国产开源之光【分布式工作流调度系统】:DolphinScheduler

DolphinScheduler是一个开源的分布式工作流调度系统,旨在帮助用户以可靠、高效和可扩展的方式管理和调度大规模的数据处理工作流。它支持以图形化方式定义和管理工作流,提供了丰富的调度功能和监控...

简单可靠高效的分布式任务队列系统

#记录我的2024#大家好,又见面了,我是GitHub精选君!背景介绍在系统访问量逐渐增大,高并发、分布式系统成为了企业技术架构升级的必由之路。在这样的背景下,异步任务队列扮演着至关重要的角色,...

虚拟服务器之间如何分布式运行?(虚拟服务器部署)

  在云计算和虚拟化技术快速发展的今天,传统“单机单任务”的服务器架构早已难以满足现代业务对高并发、高可用、弹性伸缩和容错容灾的严苛要求。分布式系统应运而生,并成为支撑各类互联网平台、企业信息系统和A...

一文掌握 XXL-Job 的 6 大核心组件

XXL-Job是一个分布式任务调度平台,其核心组件主要包括以下部分,各组件相互协作实现高效的任务调度与管理:1.调度注册中心(RegistryCenter)作用:负责管理调度器(Schedule...

京东大佬问我,SpringBoot中如何做延迟队列?单机与分布式如何做?

京东大佬问我,SpringBoot中如何做延迟队列?单机如何做?分布式如何做呢?并给出案例与代码分析。嗯,用户问的是在SpringBoot中如何实现延迟队列,单机和分布式环境下分别怎么做。这个问题其实...

企业级项目组件选型(一)分布式任务调度平台

官网地址:https://www.xuxueli.com/xxl-job/能力介绍架构图安全性为提升系统安全性,调度中心和执行器进行安全性校验,双方AccessToken匹配才允许通讯;调度中心和执...

python多进程的分布式任务调度应用场景及示例

多进程的分布式任务调度可以应用于以下场景:分布式爬虫:importmultiprocessingimportrequestsdefcrawl(url):response=re...

SpringBoot整合ElasticJob实现分布式任务调度

介绍ElasticJob是面向互联网生态和海量任务的分布式调度解决方案,由两个相互独立的子项目ElasticJob-Lite和ElasticJob-Cloud组成。它通过弹性调度、资源管控、...

分布式可视化 DAG 任务调度系统 Taier 的整体流程分析

Taier作为袋鼠云的开源项目之一,是一个分布式可视化的DAG任务调度系统。旨在降低ETL开发成本,提高大数据平台稳定性,让大数据开发人员可以在Taier直接进行业务逻辑的开发,而不用关...

SpringBoot任务调度:@Scheduled与TaskExecutor全面解析

一、任务调度基础概念1.1什么是任务调度任务调度是指按照预定的时间计划或特定条件自动执行任务的过程。在现代应用开发中,任务调度扮演着至关重要的角色,它使得开发者能够自动化处理周期性任务、定时任务和异...

取消回复欢迎 发表评论: