Skip to content

Commit 463f251

Browse files
committed
feat: 添加动态数据源类
1 parent 0735617 commit 463f251

1 file changed

Lines changed: 105 additions & 0 deletions

File tree

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
package top.cadecode.common.datasource;
2+
3+
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
4+
5+
import javax.sql.DataSource;
6+
import java.util.HashSet;
7+
import java.util.Map;
8+
import java.util.Set;
9+
10+
/**
11+
* @author Li Jun
12+
* @date 2021/12/3
13+
* @description 动态数据源类
14+
*/
15+
public class DynamicDataSource extends AbstractRoutingDataSource {
16+
17+
private boolean hasDefaultDataSource;
18+
19+
/**
20+
* 设置数据源 key
21+
*/
22+
@Override
23+
protected Object determineCurrentLookupKey() {
24+
return DynamicDataSourceHolder.getDataSourceKey();
25+
}
26+
27+
/**
28+
* 设置全部数据源
29+
*/
30+
@Override
31+
public void setTargetDataSources(Map<Object, Object> targetDataSources) {
32+
super.setTargetDataSources(targetDataSources);
33+
// 存储数据源 key
34+
DynamicDataSourceHolder.addDataSourceKeys(targetDataSources.keySet());
35+
}
36+
37+
/**
38+
* 设置默认数据源
39+
*/
40+
@Override
41+
public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
42+
super.setDefaultTargetDataSource(defaultTargetDataSource);
43+
this.hasDefaultDataSource = true;
44+
}
45+
46+
/**
47+
* 获取是否设置默认数据源
48+
*/
49+
public boolean hasDefaultDataSource() {
50+
return this.hasDefaultDataSource;
51+
}
52+
53+
/**
54+
* 切换数据源
55+
*/
56+
@Override
57+
protected DataSource determineTargetDataSource() {
58+
return super.determineTargetDataSource();
59+
}
60+
61+
/**
62+
* 动态数据源控制器
63+
*/
64+
public static class DynamicDataSourceHolder {
65+
// 定义容器,存储当前线程的数据源 key
66+
private static final ThreadLocal<String> HOLDER = new ThreadLocal<>();
67+
// 定义容器,存储所有数据源 key
68+
private static final Set<Object> KEYS = new HashSet<>();
69+
70+
/**
71+
* 设置数据源 key
72+
*/
73+
public static void setDataSourceKey(String key) {
74+
HOLDER.set(key);
75+
}
76+
77+
/**
78+
* 取出数据源 key
79+
*/
80+
public static String getDataSourceKey() {
81+
return HOLDER.get();
82+
}
83+
84+
/**
85+
* 重置数据源 key
86+
*/
87+
public static void clearDataSourceKey() {
88+
HOLDER.remove();
89+
}
90+
91+
/**
92+
* 判断是否包含数据源
93+
*/
94+
public static boolean containDataSourceKey(String key) {
95+
return KEYS.contains(key);
96+
}
97+
98+
/**
99+
* 添加数据源 key
100+
*/
101+
public static void addDataSourceKeys(Set<?> keys) {
102+
KEYS.addAll(keys);
103+
}
104+
}
105+
}

0 commit comments

Comments
 (0)