一. 引言
当前项目遇到需要连接多个数据库的场景,此时需要引入多数据源了. 还有一些诸如以下的场景:
- 与第三方对接时,有些合作方并不会为了你的某些需求而给你开发一个功能,他们可以提供给你一个可以访问数据源的只读账号,你需要获取什么数据由你自己进行逻辑处理,这时候就避免不了需要进行多数据源了
- 业务数据达到了一个量级,使用单一数据库存储达到了一个瓶颈,需要进行分库分表等操作进行数据管理,在操作数据时,不可避免的涉及到多数据源问题
网上搜索发现有不少的示例都是错误的,于是自己打算写一篇,也方便以后自己需要用到的时候拿来参考.
如果你只想要看代码请直接拉到最后看完整代码哦~ 如果你用的是Mybatis-Plus请查看官方文档↓↓↓↓ MP多数据源配置
至于MyCat、Sharding-JDBC之类的中间件我们今天不谈,只分享多数据源配置方案.
二. 实践
HikariCP项目仓库
注意: Springboot 2.0开始开始默认引入了HikariCP依赖,所以我们不需要单独引入!
HikariDataSource是 HikariCP 开放给用户使用连接池的主要操作类。所以,我们创建一个 HikariCP 的连接池,其实就是构造一个HikariDataSource.
1. 首先我们来看一下正常情况下我们配置的单数据源的配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/db_xxx?useSSL=false&autoReconnect=true&characterEncoding=utf8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
pool-name: HikariCP
minimum-idle: 5
idle-timeout: 600000
maximum-pool-size: 10
auto-commit: true
max-lifetime: 1800000
connection-timeout: 30000
connection-test-query: SELECT 1
2. 看看多数据源的配置示例(下面都以这个配置为准)
spring:
datasource:
primary:
url: jdbc:mysql://127.0.0.1:3306/db_market?useSSL=false&autoReconnect=true&characterEncoding=utf8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
pool-name: HikariCP-Primary
minimum-idle: 5
idle-timeout: 600000
maximum-pool-size: 10
auto-commit: true
max-lifetime: 1800000
connection-timeout: 30000
connection-test-query: SELECT 1
secondary:
url: jdbc:mysql://192.168.58.212:3306/db_market?useSSL=false&autoReconnect=true&characterEncoding=utf8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 12345678
type: com.zaxxer.hikari.HikariDataSource
hikari:
pool-name: HikariCP-Secondary
minimum-idle: 5
idle-timeout: 600000
maximum-pool-size: 10
auto-commit: true
max-lifetime: 1800000
connection-timeout: 30000
connection-test-query: SELECT 1
3. 接下来看看网上出现的不少这样子的例子(这里认为是错误示例)
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "usersDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
对于多数据源的配置,这里由于 hikari 这个属性对应的值还在下一层,所以使用上面这种配置是不生效的. 因为:
- 这里使用了Hikari,所以这里创建的DataSource这个Bean其实是HikariDataSource.
- @ConfigurationProperties(prefix = “spring.datasource.primary”)会将primary下的属性赋值给HikariDataSource这个Bean中的对应的属性(其实就是给HikariConfig这个赋值,更具体的信息大家可以自行搜索DataSource的初始化流程. 下面源码图中可看到HikariDataSource继承了HikariConfig).
- 但是,hikari这个属性因为是spring.datasource.primary的第二层属性,并不能正确设置进去(后面我们会验证这个问题,注意看我下图中框出来LOGGER打印那里).
4. 下面是我完整的多数据源配置类(最终版本会分成两个进行配置)
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class HikariDataSourceConfiguration {
@Primary
@Bean("primaryDataSourceProperties")
@ConfigurationProperties("spring.datasource.primary")
public DataSourceProperties primaryDataSourceProperties() {
return new DataSourceProperties();
}
@Primary
@Bean("primaryDataSource")
@Qualifier(value = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary.hikari")
public HikariDataSource primaryDataSource() {
return primaryDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
@Bean("secondaryDataSourceProperties")
@ConfigurationProperties("spring.datasource.secondary")
public DataSourceProperties secondaryDataSourceProperties() {
return new DataSourceProperties();
}
@Bean("secondaryDataSource")
@Qualifier(value = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary.hikari")
public HikariDataSource secondaryDataSource() {
return secondaryDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
参考资料(实践证明有事找官方文档是挺标准的)↓↓↓↓↓ Spring官方文档多数据配置示例
注意上面我在两个 @ConfigurationProperties(prefix = “spring.datasource.primary.hikari”) @ConfigurationProperties(prefix = “spring.datasource.secondary.hikari”) 第一、第二数据源配置都做了标记
验证我们上面说的配置失效的问题,步骤: 1、当我们注释掉这两行,此时的配置就相当于是上面提到的错误示例的样子了 2、多数据源配置以上面代码为准,我分别设置两个数据源的连接池名称是HikariCP-Primary、HikariCP-Secondary,再结合最上面贴图红框中HikariDataSource构造方法知道Bean初始化时会打印数据池名称
LOGGER.info(“{} - Starting…”, configuration.getPoolName());
3、启动项目,查看控制台 此时,你会发现,数据源初始化出来的并不是我们需要的,这足以说明我们配置的spring.datasource.primary.hikari这一层属性没有被正确地设置到HikariConfig中(虽然能跑起来,可以正确连接到对应的数据源,但是其它的配置并未生效),而是HikariConfig在初始化时自动给每个数据源加上了名字,可以见以下源码(HikariConfig.class) 假如,这时候我们把 第一、第二数据源配置上面的@ConfigurationProperties(prefix = “spring.datasource.primary.hikari”)注解打开,再启动项目,则可以清晰地看到我们自己设置的属性被应用到了HikariConfig中. 这时候就可以正常地读入hikari连接池的配置了.
有不理解的可以自己看看DataSource的初始化流程即可.
5. 接下来我们做一下测试
import cn.hutool.json.JSONUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
@SpringBootTest
public class MultiDataSourceTest {
@Resource
private JdbcTemplate primaryJdbcTemplate;
@Resource
private JdbcTemplate secondaryJdbcTemplate;
@Resource(name = "primaryDataSource")
private DataSource primaryDataSource;
@Resource(name = "secondaryDataSource")
private DataSource secondaryDataSource;
@Test
public void testPrimaryDataSourceConnect() {
String sql = "SELECT * FROM `apk_category`";
List<Map<String, Object>> result = primaryJdbcTemplate.queryForList(sql);
System.out.println("primary data source :\t"+ JSONUtil.toJsonStr(result));
}
@Test
public void testSecondaryDataSourceConnect() {
String sql = "SELECT * FROM `apk_category`";
List<Map<String, Object>> result = secondaryJdbcTemplate.queryForList(sql);
System.out.println("secondary data source :\t"+ JSONUtil.toJsonStr(result));
}
@Test
void testGetConnection() {
try (Connection connection = primaryDataSource.getConnection()) {
System.out.println("获取到的primaryDataSource连接对象" + connection);
} catch (SQLException e) {
e.printStackTrace();
}
try (Connection connection = secondaryDataSource.getConnection()) {
System.out.println("获取到的secondaryDataSource连接对象" + connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
三.完整代码
- PrimaryDataSourceConfiguration.class
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.market.mapper", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfiguration {
public static final String MAPPER_LOCATION = "classpath:mapper/*.xml";
@Primary
@Bean("primaryDataSourceProperties")
@ConfigurationProperties("spring.datasource.primary")
public DataSourceProperties primaryDataSourceProperties() {
return new DataSourceProperties();
}
@Primary
@Bean("primaryDataSource")
@Qualifier(value = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary.hikari")
public HikariDataSource primaryDataSource() {
return primaryDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
@Bean(name = "primaryTransactionManager")
@Primary
public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Primary
@Bean(name = "primarySqlSessionFactory")
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(PrimaryDataSourceConfiguration.MAPPER_LOCATION));
return sessionFactoryBean.getObject();
}
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
- SecondaryDataSourceConfiguration.class
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.market.mapper2", sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryDataSourceConfiguration {
public static final String MAPPER_LOCATION = "classpath:mapper2/*.xml";
@Bean("secondaryDataSourceProperties")
@ConfigurationProperties("spring.datasource.secondary")
public DataSourceProperties secondaryDataSourceProperties() {
return new DataSourceProperties();
}
@Bean("secondaryDataSource")
@Qualifier(value = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary.hikari")
public HikariDataSource secondaryDataSource() {
return secondaryDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
@Bean(name = "secondaryTransactionManager")
public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(SecondaryDataSourceConfiguration.MAPPER_LOCATION));
return sessionFactoryBean.getObject();
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
说明一下: 之前我们使用@Transactional的时候,并没有通过value或者transactionManager设置事务管理器,这是为什么? 这是因为我们在spring容器中只定义了一个事务管理器,spring启动事务的时候,默认会按类型在容器中查找事务管理器,刚好容器中只有一个,就拿过来用了,如果有多个的时候,如果你不指定,spring是不知道具体要用哪个事务管理器的。
使用事务时大概是这样子: @Transactional(transactionManager = “transactionManager1”, propagation = Propagation.REQUIRED)
至于你后面获取到不同的数据源如何操作取决于你自己了.
|