1.背景在本文中,我们使用Seata来整合多数据源。我们使用dynamic-datasource-spring-boot-starter来完成多数据源切换的功能,这个组件也可以和Seata集成来实现数据源的代理。本文依赖之前的seata集成nacos完成分布式部署。二、集成步骤1、搭建seata服务器。Seata集成nacos完成分布式部署。2.引入数据源切换组件com.baomidoudynamic-datasource-spring-boot-starter3.4.13。引入seata组件io.seataseata-spring-boot-starter1.4.2com.alibaba.nacosnacos-client1.3.24、这里配置多数据源配置account和order2个数据源,设置并与seata集成。您需要注册这方面的位置。设置默认数据源spring:datasource:dynamic:#开启seataseata:true#mode为at模式seata-mode:at#主要数据源为account数据源primary:account#不开启strict模式strict:false#配置数据源部分的位置order:"-2147483648"#每个数据源datasource:#账库的数据源account:url:jdbc:mysql://127.0.0.1:3306/seata_account?useUnicode=true&characterEncoding=utf8&autoReconnectForPools=true&useSSL=falseusername:rootpassword:rootdriver-class-name:com.mysql.cj.jdbc.Driver#订单库order的数据源:url:jdbc:mysql://127.0.0.1:3306/seata_order?useUnicode=true&characterEncoding=utf8&autoReconnectForPools=true&useSSL=false用户名:root密码:root驱动程序类名:com.mysql.cj.jdbc.Driver5。关闭seata的默认数据源代理seata:#是否自动开启数据源代理enable-auto-data-source-proxy:false6.配置seata事务组seata:enabled:truetx-service-group:tx_multiple_datasource_group#该组需要存在于seata服务器的配置中心,即seata服务器的配置中心需要有一个服务。vgroupMapping.tx_multiple_datasource_group配置项7,业务库创建undo_log表CREATETABLEIFNOTEXISTS`undo_log`(`branch_id`BIGINTNOTNULLCOMMENT'分支事务id',`xid`VARCHAR(128)NOTNULLCOMMENT'全局事务id',`context`VARCHAR(128)NOTNULLCOMMENT'undo_log上下文,比如序列化',`rollback_info`LONGBLOBNOTNULLCOMMENT'回滚信息',`log_status`INT(11)NOTNULLCOMMENT'0:正常状态,1:防御状态',`log_created`DATETIME(6)NOTNULLCOMMENT'创建日期时间',`log_modified`DATETIME(6)NOTNULLCOMMENT'modifydatetime',UNIQUEKEY`ux_undo_log`(`xid`,`branch_id`))ENGINE=InnoDBCOMMENT='ATtransactionmodeundotable';8、xid的传递9、在代码中使用数据源切换10、业务方法开启分布式事物,集成完成。三、注意事项1、启动事物需要获取数据库连接,所以我们切换数据源的@DS注解必须在@Transaction之前执行。4.完整代码https://gitee.com/huan1993/spring-cloud-parent/tree/master/seata/seata-multiple-datasource