配置文件

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
#database1
spring.datasource.wh.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.wh.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.wh.jdbcUrl=jdbc:mysql://192.168.1.130:3306/wh?zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.wh.username=root
spring.datasource.wh.password=root
spring.datasource.wh.minimum-idle=1
spring.datasource.wh.maximum-pool-size=15
spring.datasource.wh.auto-commit=true
spring.datasource.wh.idle-timeout=60000
spring.datasource.wh.pool-name=wuhan
spring.datasource.wh.max-lifetime=1800000
spring.datasource.wh.connection-timeout=30000
spring.datasource.wh.connection-test-query=SELECT 1

#database2
spring.datasource.es.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.es.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.es.jdbcUrl=jdbc:mysql://192.168.1.130:3306/es?zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.es.username=root
spring.datasource.es.password=root
spring.datasource.es.minimum-idle=1
spring.datasource.es.maximum-pool-size=15
spring.datasource.es.auto-commit=true
spring.datasource.es.idle-timeout=60000
spring.datasource.es.pool-name=enshi
spring.datasource.es.max-lifetime=1800000
spring.datasource.es.connection-timeout=30000
spring.datasource.es.connection-test-query=SELECT 1

前置动态处理DataSourceHolder【利用Interceptor + reqHeader】

CityEnum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public enum CityEnum {
/*武汉*/
wuhan("wuhan"),
/*恩施*/
enshi("enshi");

private String city;

CityEnum(String city) {
this.city = city;
}

public String getCity() {
return city;
}
}

DataSourceHolder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class DataSourceHolder {
//线程本地环境
private static final ThreadLocal<String> contextHolders = new ThreadLocal<>();

//设置数据源
public static void setDataSource(String customerType) {
contextHolders.set(customerType);
}

//获取数据源
public static String getDataSource() {
return contextHolders.get();
}

//清除数据源
public static void clearDataSource() {
contextHolders.remove();
}
}

DynamicDataSourceInterceptor

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
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author best
*/
@Component
public class DynamicDataSourceInterceptor implements HandlerInterceptor {

//在业务处理器处理请求之前被调用
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String city = request.getHeader("city");
if (StringUtils.isBlank(city)) {
city = CityEnum.wuhan.getCity();
}
DataSourceHolder.setDataSource(city);
//RequestCityHolder.add(city);
System.err.println(city + "处理开始...");
return true;
}

//请求完成之后
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
String city = request.getHeader("city");
if (StringUtils.isBlank(city)) {
city = CityEnum.wuhan.getCity();
}
//清除数据源
DataSourceHolder.clearDataSource();
//清除ThreadLocal变量
//RequestCityHolder.remove();
System.err.println(city + "处理完成...");
}
}

DynamicRoutingDataSource

1
2
3
4
5
6
7
8
9
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

@Override
protected Object determineCurrentLookupKey() {
return DataSourceHolder.getDataSource();
}
}

DynamicDataSourceConfiguration

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
84
85
86
87
88
89
90
91
92
93
94
95
import com.zaxxer.hikari.HikariDataSource; 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
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.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
* 数据源ben
*/
@MapperScan(basePackages = "xxx.xx.mapper")
@Configuration
public class DynamicDataSourceConfiguration {

/**
* 武汉数据源
* @return
*/
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.wh")
public DataSource wuhan(){
return new HikariDataSource();
}

/**
* 恩施数据源
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource.es")
public DataSource enshi(){
return new HikariDataSource();
}

/**
* 核心动态数据源配置
* @return
*/
@Bean
public DataSource dynamicDataSource(){
DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
Map<Object,Object> dataSourceMap = new HashMap<>(2);
//设置默认数据源
dataSource.setDefaultTargetDataSource(wuhan());
//配置数据源
dataSourceMap.put(CityEnum.wuhan.getCity(),wuhan());
dataSourceMap.put(CityEnum.enshi.getCity(),enshi());
dataSource.setTargetDataSources(dataSourceMap);
return dataSource;
}

/**
* sql工厂
* @return
* @throws Exception
*/
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dynamicDataSource());
//此处设置为了解决找不到mapper文件的问题
sqlSessionFactoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:mapping/*.xml"));
return sqlSessionFactoryBean.getObject();
}

/**
* sql模板
* @return
* @throws Exception
*/
@Bean
public SqlSessionTemplate sqlSessionTemplate() throws Exception {
return new SqlSessionTemplate(sqlSessionFactory());
}

/**
* 事务管理
* @return
*/
@Bean
public PlatformTransactionManager platformTransactionManager(){
return new DataSourceTransactionManager(dynamicDataSource());
}
}