DynamicDataSource.java
1.21 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
package com.huaheng.framework.datasource;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态数据源
*
* @author huaheng
*/
public class DynamicDataSource extends AbstractRoutingDataSource
{
private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
{
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
public DynamicDataSource(){
}
@Override
protected Object determineCurrentLookupKey()
{
Object lookupKey = contextHolder.get();
return lookupKey;
}
public static void master(){
contextHolder.set(DatabaseType.Master);
}
public static void slave() {
contextHolder.set(DatabaseType.Slave);
}
public static void clear() {
contextHolder.remove();
}
public static DatabaseType getType() {
return contextHolder.get();
}
public enum DatabaseType {
Master, Slave
}
}