Mybatis plus Dynamic Datasource 动态数据源及使用方式
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_22.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);到此这篇关于Mybatis plus Dynamic Datasource 动态数据源及使用方式的文章就介绍到这了,更多相关Mybatis plus动态数据源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringCloud使用AOP统一处理Web请求日志实现步骤
这篇文章主要为大家介绍了SpringCloud使用AOP统一处理Web请求日志实现步骤,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-08-08
最新IntelliJ IDEA 2021版配置 Tomcat 8.5 的详细步骤
idea开发工具一直是java环境最好用,很受广大开发者喜爱,今天通过本文给大家分享最新IntelliJ IDEA 2021版配置 Tomcat 8.5 的详细步骤,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友可以参考下2021-06-06
maven settings.xml文件的存放及配置(包含了配置阿里云镜像)
本文详细解释了Maven中settings.xml文件的存放位置,以及用户级别和全局级别的区别,重点介绍了localRepository、交互模式、离线模式、插件组、代理设置、服务器认证、镜像列表和激活profiles的使用方法,感兴趣的可以了解一下2025-09-09
Java中的List和MySQL中的varchar相互转换的解决方案
实体类中有一个 List<String> 类型的属性,对应于 MySQL 表里的 varchar 字段,使用 MyBatis 添加或查询时能互相转换,本文给大家介绍Java中的List和MySQL中的varchar相互转换的解决方案,需要的朋友可以参考下2024-06-06
SpringBoot中的PropertySource原理详解
这篇文章主要介绍了SpringBoot中的PropertySource原理详解,PropertySource 是一个非常重要的概念,它允许您在应用程序中定义属性,并将这些属性注入到 Spring 环境中,需要的朋友可以参考下2023-07-07
Java报错:java.util.concurrent.ExecutionException的解决办法
在Java并发编程中,我们经常使用java.util.concurrent包提供的工具来管理和协调多个线程的执行,va并发编程中,然而,在使用这些工具时,可能会遇到各种各样的异常,其中之一就是java.util.concurrent.ExecutionException,本文将详细分析这种异常的背景、可能的原因2024-09-09


最新评论