Mybatis plus:Dynamic Datasource 动态数据源
dynamic-datasource-spring-boot-starter 是一个基于springboot的快速集成多数据源的启动器。它跟mybatis-plus是一个生态圈里的,很容易集成mybatis-plus。
·
1 介绍
dynamic-datasource-spring-boot-starter 是一个基于springboot的快速集成多数据源的启动器。它跟mybatis-plus是一个生态圈里的,很容易集成mybatis-plus。
1.1 特点
- 支持 数据源分组 ,适用于多种场景 纯粹多库 读写分离 一主多从 混合模式。
- 支持数据库敏感配置信息 加密(可自定义) ENC()。
- 支持每个数据库独立初始化表结构schema和数据库database。
- 支持无数据源启动,支持懒加载数据源(需要的时候再创建连接)。
- 支持 自定义注解 ,需继承DS(3.2.0+)。
- 提供并简化对Druid,HikariCp,BeeCp,Dbcp2的快速集成。
- 提供对Mybatis-Plus,Quartz,ShardingJdbc,P6sy,Jndi等组件的集成方案。
- 提供 自定义数据源来源 方案(如全从数据库加载)。
- 提供项目启动后 动态增加移除数据源 方案。
- 提供Mybatis环境下的 纯读写分离 方案。
- 提供使用 spel动态参数 解析数据源方案。内置spel,session,header,支持自定义。
- 支持 多层数据源嵌套切换 。(ServiceA >>> ServiceB >>> ServiceC)。
- 提供 基于seata的分布式事务方案 。
- 提供 本地多数据源事务方案。
1.2 约定
- 本框架只做 切换数据源 这件核心的事情,并不限制你的具体操作,切换了数据源可以做任何CRUD。
- 配置文件所有以下划线
_
分割的数据源 首部 即为组的名称,相同组名称的数据源会放在一个组下。 - 切换数据源可以是组名,也可以是具体数据源名称。组名则切换时采用负载均衡算法切换。
- 默认的数据源名称为 master ,你可以通过
spring.datasource.dynamic.primary
修改。 - 代码块里主动切换>方法上的注解优>类上注解(就近原则)。
- DS支持继承抽象类上的DS,支持继承接口上的DS。
2 使用方式
2.1 引入依赖
- spring-boot 1.5.x 2.x.x
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${version}</version>
</dependency>
- spring-boot3及以上
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
<version>${version}</version>
</dependency>
2.2 配置数据源
spring:
datasource:
dynamic:
enabled: true #启用动态数据源,默认true
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
grace-destroy: false #是否优雅关闭数据源,默认为false,设置为true时,关闭数据源时如果数据源中还存在活跃连接,至多等待10s后强制关闭
datasource:
master:
url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
slave_1:
url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave_2:
url: ENC(xxxxx) # 内置加密,使用请查看详细文档
username: ENC(xxxxx)
password: ENC(xxxxx)
driver-class-name: com.mysql.jdbc.Driver
#......省略
#以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2
2.2.1 多主多从
spring:
datasource:
dynamic:
datasource:
master_1:
master_2:
slave_1:
slave_2:
slave_3:
2.2.2 纯粹多库
spring:
datasource:
dynamic:
datasource:
mysql:
oracle:
sqlserver:
postgresql:
h2:
2.2.3 混合配置
spring:
datasource:
dynamic:
datasource:
master:
slave_1:
slave_2:
oracle_1:
oracle_2:
2.3 使用 @DS 切换数据源
@DS 可以注解在方法上或类上,同时存在就近原则 方法上注解 优先于 类上注解。
注解 | 结果 |
---|---|
没有@DS | 默认数据源 |
@DS("dsName") | dsName可以为组名也可以为具体某个库的名称 |
@Service
@DS("slave")
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List selectAll() {
return jdbcTemplate.queryForList("select * from user");
}
@Override
@DS("slave_1")
public List selectByCondition() {
return jdbcTemplate.queryForList("select * from user where age >10");
}
}
2.4 使用代码切换数据源
DynamicDataSourceContextHolder 用于动态切换数据源的上下文工具类。在使用多数据源的情况下,它可以帮助在运行时选择要使用的数据源。存储当前线程的数据源标识:
// 切换到slave数据库
DynamicDataSourceContextHolder.push("slave");
2.5 添加新的数据源
@Resource
private DataSource dataSource;
@Resource
private DefaultDataSourceCreator dataSourceCreator;
public void add(){
DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
// 配置数据源
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setLazy(true);
dataSourceProperty.setUsername("root");
dataSourceProperty.setPassword("123456");
dataSourceProperty.setUrl(url);
dataSourceProperty.setDriverClassName(driverClassName);
// 添加数据源
ds.addDataSource(key, dataSourceCreator.createDataSource(dataSourceProperty));
}
3 使用mybatis创建数据库
定义mapper
@Mapper
public interface DatabaseMapper {
@Select("CREATE DATABASE IF NOT EXISTS ${databaseName}")
void createDatabase( String databaseName);
}
执行代码:
// 配置数据源
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setLazy(true);
dataSourceProperty.setUsername(username);
dataSourceProperty.setPassword(password);
dataSourceProperty.setUrl(url);
dataSourceProperty.setDriverClassName(driverClassName);
// 创建sqlSessionFactory,配置mapper类
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.addMapper(DatabaseMapper.class);
sqlSessionFactoryBean.setConfiguration(configuration);
sqlSessionFactoryBean.setDataSource(dataSourceCreator.createDataSource(dataSourceProperty));
// 获取sqlSession
SqlSession sqlSession = Objects.requireNonNull(sqlSessionFactoryBean.getObject()).openSession();
DatabaseMapper mapper = sqlSession.getMapper(DatabaseMapper.class);
// 初始化数据库,参数为数据库名注意要使用 `` 包裹起来。
mapper.createDatabase("`databaseName`");
4 使用SpringJDBC运行sql脚本
使用SQL脚本中定义的外部资源进行初始化或清理数据库。
ResourceDatabasePopulator popular = new ResourceDatabasePopulator();
// xxx.sql 为resource目录下文件。
popular.addScript(new ClassPathResource("xxx.sql"));
// 传入数据源执行sql脚本。
popular.execute(dataSource);

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)