1. 添加 maven 依赖

在 pom.xml 中添加对应的依赖

1
2
3
4
5
6
7
8
9
10
11
12
<dependencies>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>

2. 配置 configuration

2.1 配置 dataSource 数据源

我们这里使用的是druid数据库连接池
Druid 是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。Druid 已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。Druid 是阿里巴巴开发的号称为监控而生的数据库连接池!

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
@Configuration
public class DataSourceConfig {

private final Environment environment;

@Autowired
public DataSourceConfig(Environment environment) {
this.environment = environment;
}


@Bean("primaryDataSource")
DataSource primaryDataSource() {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
dataSource.setUrl(environment.getProperty("spring.datasource.druid.primary.url"));
dataSource.setUsername(environment.getProperty("spring.datasource.druid.primary.username"));
dataSource.setPassword(environment.getProperty("spring.datasource.druid.primary.password"));
return dataSource;
}

@Bean("secondDataSource")
DataSource secondDataSource() {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
dataSource.setUrl(environment.getProperty("spring.datasource.druid.second.url"));
dataSource.setUsername(environment.getProperty("spring.datasource.druid.second.username"));
dataSource.setPassword(environment.getProperty("spring.datasource.druid.second.password"));
return dataSource;
}

}

2.2 在 application.yml 中添加对应配置

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
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
primary:
url: jdbc:mysql://localhost:3306/primary?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
username: root
password: root
second:
url: jdbc:mysql://localhost:3306/second?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
username: root
password: root
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: admin
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
jpa:
hibernate:
ddl-auto: none
show-sql: true
open-in-view: false
database: mysql

2.3 为每一个数据源创建 jpa 配置类

配置 Primary 数据源

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
@Configuration
@EntityScan(basePackages = "com.hvnobug.jmds.entity.primary")
//1、实体扫描
//2、实体管理 ref
//3、事务管理
@EnableJpaRepositories(
basePackages = "com.hvnobug.jmds.repository.primary",
entityManagerFactoryRef = "primaryEntityManagerFactory",
transactionManagerRef = "primaryTransactionManager")
@EnableTransactionManagement
public class PrimaryJpaConfig {

private final DataSource dataSource;

private final JpaProperties jpaProperties;

@Autowired
public PrimaryJpaConfig(@Qualifier("primaryDataSource") DataSource dataSource, JpaProperties jpaProperties) {
this.dataSource = dataSource;
this.jpaProperties = jpaProperties;
}


@Bean("primaryEntityManagerFactory")
@Primary
public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory =
new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource);
factory.setPackagesToScan("com.hvnobug.jmds.repository.primary","com.hvnobug.jmds.entity.primary");
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factory.setJpaProperties(jpaProperties());
return factory;
}

// EntityManager 不过解释,用过 jpa 的应该都了解
@Bean(name = "primaryEntityManager")
@Primary
public EntityManager entityManager() {
return Objects.requireNonNull(primaryEntityManagerFactory().getObject()).createEntityManager();
}

// jpa 事务管理
@Bean(name = "primaryTransactionManager")
@Primary
public JpaTransactionManager transactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(primaryEntityManagerFactory().getObject());
return jpaTransactionManager;
}

}

配置 Second 数据源

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
@Configuration
@EntityScan(basePackages = "com.hvnobug.jmds.entity.second")
//1、实体扫描
//2、实体管理 ref
//3、事务管理
@EnableJpaRepositories(
basePackages = "com.hvnobug.jmds.repository.second",
entityManagerFactoryRef = "secondEntityManagerFactory",
transactionManagerRef = "secondTransactionManager")
@EnableTransactionManagement
public class SecondJpaConfig {

private final DataSource dataSource;

@Autowired
public SecondJpaConfig(@Qualifier("secondDataSource") DataSource dataSource, JpaProperties jpaProperties) {
this.dataSource = dataSource;
this.jpaProperties = jpaProperties;
}

@Bean("secondEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory =
new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource);
factory.setPackagesToScan("com.hvnobug.jmds.repository.second","com.hvnobug.jmds.entity.second");
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factory.setJpaProperties(jpaProperties());
return factory;
}

// EntityManager 不过解释,用过 jpa 的应该都了解
@Bean(name = "secondEntityManager")
public EntityManager entityManager() {
return Objects.requireNonNull(secondEntityManagerFactory().getObject()).createEntityManager();
}

// jpa 事务管理
@Bean(name = "secondTransactionManager")
public JpaTransactionManager transactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(secondEntityManagerFactory().getObject());
return jpaTransactionManager;
}

}

此时 Spring 会为 com.hvnobug.jmds.repository.primary 包下的 Repository 注入 Primary 数据源
会为 com.hvnobug.jmds.repository.second 包下的 Repository 注入 Second 数据源