A springboot tool that provides dynamic data sources
https://gitee.com/wdyun
dynamic-datasource-spring-boot-starter
-------------------------------------------------------------------------------
English Documentation
dynamic-datasource-spring-boot-starter是基于springboot开发的一款多数据源动态切换的开发工具。
只需在springboot项目中导入依赖 即可方便快捷的开发多数据源项目,并且支持多数据源的分布式事务。
为您的多数据源项目开发保驾护航。
专门为springboot项目提供动态数据源支持的开源java项目
旨在提供多数据源的一键式支持。
在项目的pom.xml的dependencies中加入以下内容:
<dependency>
<groupId>com.enbatisgroupId>
<artifactId>dynamic-datasource-spring-boot-starterartifactId>
<version>${最新版本}version>
dependency>
在yml文件里面添加多数据源的配置
spring:
datasource:
dynamic:
name: master,slave
default: master
master:
type: com.alibaba.druid.pool.xa.DruidXADataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: xxx
password: xxxxxxx
url: jdbc:mysql://xxxxx:3306/test01?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
initialSize: 5
minIdle: 5
maxActive: 20
slave:
type: com.alibaba.druid.pool.xa.DruidXADataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: xxx
password: xxxxxxx
url: jdbc:mysql://xxxxx:3306/test02?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
initialSize: 5
minIdle: 5
maxActive: 20
在mapper接口添加数据源的配置(默认数据源可不添加)
(master为默认的数据源)
@MybatisMapper(name = "master")
public interface SysUserMapper extends BaseMapper<SysUser> {
List<SysUser> list1();
}
@MybatisMapper(name = "slave")
public interface SysUserMapper2 extends BaseMapper<SysUser> {
}
使用分布式事务示例如下(只需在需要事务的方法上加入DynamicTx注解)
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper,SysUser > implements SysUserService {
@DynamicTx
@Override
public boolean tx() {
SysUser sysUser = new SysUser();
sysUser.setId(IdWorker.getId());
sysUser.setSex("男");
sysUser.setUsername("sysUserMapper1");
baseMapper.addEntity(sysUser);
System.out.println(10/0);
SysUser sysUser2 = new SysUser();
sysUser2.setId(IdWorker.getId());
sysUser2.setSex("男");
sysUser2.setUsername("sysUserMapper2");
sysUserMapper2.addEntity(sysUser2);
return false;
}
}
https://gitee.com/wdyun/hrm
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(64) NOT NULL COMMENT '主键',
`username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户',
`sex` char(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'sex',
`deleted` int(2) NULL DEFAULT 0,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES (1443577766556602368, 'test01', '男', 0);
SET FOREIGN_KEY_CHECKS = 1;