DataSourceConfig.java
1.65 KB
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
package com.sincere.quartz.datasource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* 数据源配置
*
*/
@Configuration
public class DataSourceConfig {
@Bean(name = "master")
@ConfigurationProperties(prefix = "datasource.master")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "slave")
@ConfigurationProperties(prefix = "datasource.slave")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
@Bean(name = "yxy")
@ConfigurationProperties(prefix = "datasource.yxy")
public DataSource dataSource3() {
return DataSourceBuilder.create().build();
}
@Bean(name="dynamicDataSource")
@Primary //优先使用,多数据源
public DataSource dataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
DataSource master = dataSource1();
DataSource slave = dataSource2();
DataSource yxy = dataSource3();
//设置默认数据源
dynamicDataSource.setDefaultTargetDataSource(master);
//配置多数据源
Map<Object,Object> map = new HashMap<>();
map.put(DataSourceType.Master.getName(), master); //key需要跟ThreadLocal中的值对应
map.put(DataSourceType.Slave.getName(), slave);
map.put(DataSourceType.Yxy.getName(), yxy);
dynamicDataSource.setTargetDataSources(map);
return dynamicDataSource;
}
}