业务描述: 在微服务搭建中经常会使用到多数据库情形这个时候,多数据源的切换将显得尤为重要下面是以Mysql数据库为数据源来实现的多数据源的切换方案之一。
实现过程:
1、 编写SpringCloud服务项目的配置文件,通常是修改项目中resources包下的bootstrap.yml文件(PS:也有可能是application.yml文件)这里使用yml文件格式来编写配置。
spring:
#MySql数据源
datasource:
#test1数据库配置
test1:
#数据库连接地址
jdbc-url: jdbc:mysql://${
数据库连接地址IP}:${
数据库连接端口号}/${
数据库名称}?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
#数据库用户名
username: ${
用户名}
#数据库密码
password: ${
密码}
#数据库连接类型这里使用了阿里巴巴的Druid连接方案,引入后会自动配置driver-class-name所需要的类型
type: com.alibaba.druid.pool.DruidDataSource
#默认初始化连接数
initialSize: 5
#最小连接数
minIdle: 5
#最大连接书
maxActive: 50
#连接等待时间
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
#测试连接
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 50
filters: stat
asyncInit: true
#test2数据库配置
#属性内容同上
test2:
jdbc-url: jdbc:mysql://${
数据库连接地址IP}:${
数据库连接端口号}/${
数据库名称}?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
username: ${
用户名}
password: ${
密码}
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 50
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 50
filters: stat
asyncInit: true
2、 在项目中创建config->mybatis包在其中进行实现多数据源的编写(PS:也可以放在别的包下这个包是自定义的)
3、 新建DataSourceConfig类用来注入Mysql数据的配置创建连接池并注入事务管理
代码如下:
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.</