DynamicDataSource.java
1.95 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
58
59
package com.dili.titan.common.datasource;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* 动态数据源.
* @author zhoumin@360buy.com
* 2011-9-13 下午6:12:18
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
private Map<String, DataSource> masterDataSources;
private Map<String, DataSource> slaveDataSources;
private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);
@PostConstruct
public void setTargetDataSources() {
Map<Object, Object> allDataSource = new HashMap<Object, Object>();
if (masterDataSources != null) {
allDataSource.putAll(masterDataSources);
}
if (masterDataSources != null) {
allDataSource.putAll(slaveDataSources);
}
super.setTargetDataSources(allDataSource);
}
@Override
protected Object determineCurrentLookupKey() {
String lookupKey = DataSourceSwitcher.getDataSource();
if(StringUtils.isNotEmpty(lookupKey) && lookupKey.indexOf(DataSourceSwitcher.READ)>=0){
lookupKey = DataSourceSwitcher.READ+(DataSourceSwitcher.RANDOM.nextInt(slaveDataSources.size()) + 1);
}
log.debug("获取数据源" + lookupKey);
return lookupKey;
}
public Map<String, DataSource> getMasterDataSources() {
return masterDataSources;
}
public void setMasterDataSources(Map<String, DataSource> masterDataSources) {
this.masterDataSources = masterDataSources;
}
public Map<String, DataSource> getSlaveDataSources() {
return slaveDataSources;
}
public void setSlaveDataSources(Map<String, DataSource> slaveDataSources) {
this.slaveDataSources = slaveDataSources;
}
}