mybatis+druid双数据源

因为公司中项目涉及到2个不同的数据库,因此需要设置双数据源,这里采用的是druid+mybatis框架进行数据源切换

1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.13</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://******:3307/themis_db?useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai&useLegacyDatetimeCode=false
username: root
password: ******
driver-class-name: com.mysql.jdbc.Driver
max-idle: 10
max-wait: 10000
min-idle: 5
initial-size: 5
test-on-borrow: false
test-while-idle: true
time-between-eviction-runs-millis: 18800
druid:
domestic1:
url: jdbc:mysql://*****:3308/ailaoyizhu_db?useUnicode=true&characterEncoding=utf8
username: root
password: ******
#初始大小
initial-size: 1
#最大连接数
max-active: 100
#最最小空闲连接数
min-idle: 10
#配置获取连接等待超时的时间
max-wait: 60000
default-auto-commit: true
#池的准备好的语句
# pool-prepared-statements: true
#每个连接大小的MAX池准备语句
max-pool-prepared-statement-per-connection-size: 20

数据源构造器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.yilvs.config;

import com.alibaba.druid.pool.DruidDataSource;

/**
* @Author mintaoyu
* Date on 2020-11-16 16:05
*/
public class DruidDataSourceBuilder {

private DruidDataSource dataSource = new DruidDataSource();

public final static DruidDataSourceBuilder newInstance() {
return new DruidDataSourceBuilder();
}

public DruidDataSourceBuilder appendDriverClassName(String driverClassName) {
dataSource.setDriverClassName(driverClassName);
return this;
}

public DruidDataSourceBuilder appendUrl(String url) {
dataSource.setUrl(url);
return this;
}

public DruidDataSourceBuilder appendUsername(String username) {
dataSource.setUsername(username);
return this;
}

public DruidDataSourceBuilder appendPassword(String password) {
dataSource.setPassword(password);
return this;
}

public DruidDataSourceBuilder appendInitialSize(int initialSize) {
dataSource.setInitialSize(initialSize);
return this;
}

public DruidDataSourceBuilder appendMinIdle(int minIdle) {
dataSource.setMinIdle(minIdle);
return this;
}

public DruidDataSourceBuilder appendMaxActive(int maxActive) {
dataSource.setMaxActive(maxActive);
return this;
}

public DruidDataSourceBuilder appendMaxWait(long maxWait) {
dataSource.setMaxWait(maxWait);
return this;
}
public DruidDataSource getDataSource() {
return dataSource;
}

}

主数据源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.yilvs.config;

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.beans.factory.annotation.Value;
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.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
* 主数据源
*/
@Configuration
@MapperScan(basePackages = AbroadDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "abroadSqlSessionFactory")
public class AbroadDataSourceConfig {

// 设置Mapper的路径
static final String PACKAGE = "com.yilvs.*.mapper";
// 设置mapper-xml的路径
static final String MAPPER_LOCATION = "classpath:mapper/robot/*.xml";

@Value("${spring.datasource.driver-class-name}")
private String driverClassName;

@Value("${spring.datasource.url}")
private String url;

@Value("${spring.datasource.username}")
private String username;

@Value("${spring.datasource.password}")
private String password;

@Value("${spring.datasource.druid.initial-size}")
private int initialSize;

@Value("${spring.datasource.druid.min-idle}")
private int minIdle;

@Value("${spring.datasource.druid.max-active}")
private int maxActive;

@Value("${spring.datasource.druid.max-wait}")
private int maxWait;

@Bean(name = "abroadDataSource")
@Primary
public DataSource abroadDataSource() {
return DruidDataSourceBuilder.newInstance()
.appendDriverClassName(driverClassName)
.appendUrl(url)
.appendUsername(username)
.appendPassword(password)
.appendInitialSize(initialSize)
.appendMinIdle(minIdle)
.appendMaxActive(maxActive)
.appendMaxWait(maxWait)
.getDataSource();
}

@Bean(name = "abroadTransactionManager")
@Primary
public DataSourceTransactionManager abroadTransactionManager() {
return new DataSourceTransactionManager(abroadDataSource());
}

@Bean(name = "abroadSqlSessionFactory")
@Primary
public SqlSessionFactory abroadSqlSessionFactory(@Qualifier("abroadDataSource") DataSource abroadDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(abroadDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(AbroadDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}

从数据源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.yilvs.config;


import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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.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.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
* 从数据源
*/
@Configuration
@MapperScan(basePackages = Domestic1DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "domestic1SqlSessionFactory")
public class Domestic1DataSourceConfig {

static final String PACKAGE = "com.yilvs.ailao.sql";
static final String MAPPER_LOCATION = "classpath:mapper/ailao/*.xml";

@Bean(name = "domestic1DataSource")
@ConfigurationProperties("spring.datasource.druid.domestic1")
public DataSource domestic1DataSource() {
return DruidDataSourceBuilder.create().build();
}

@Bean(name = "domestic1TransactionManager")
public DataSourceTransactionManager domestic1TransactionManager() {
return new DataSourceTransactionManager(domestic1DataSource());
}

@Bean(name = "domestic1SqlSessionFactory")
public SqlSessionFactory abroadSqlSessionFactory(@Qualifier("domestic1DataSource") DataSource domestic1DataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(domestic1DataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(Domestic1DataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();

}
}

以上配置就能够根据你不同的Mapper扫描器去选择不同的数据源来进行操作,比如mapper放在com.yilvs.ailao.sql中,即使用从数据源进行操作,放在com.yilvs.*.mapper中就会使用主数据源

疑惑

如果启动失败,记得Application中还要设置@MapperScan

赏个🍗吧
0%