<bean id="dataSource" class="com.wang.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="dataSource1" value-ref="dataSource1"></entry>
<entry key="dataSource2" value-ref="dataSource2"></entry>
</map>
</property>
</bean>
<bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />
<property name="maxWait" value="60000" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="20" />
<property name="filters" value="stat" />
</bean>
<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />
<property name="maxWait" value="60000" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="20" />
<property name="filters" value="stat" />
</bean>
public class DynamicDataSource extends AbstractRoutingDataSource {
public static ConcurrentMap<Thread, String> key = new ConcurrentHashMap<>();
@Override
protected Object determineCurrentLookupKey() {
return key.get(Thread.currentThread());
}
@Override
public void setTargetDataSources(Map<Object, Object> targetDataSources) {
MysqlDataSource ds = new MysqlDataSource();
ds.setURL("jdbc:mysql://127.0.0.1/wang");
ds.setUser("root");
ds.setPassword("root");
targetDataSources.put("dynamicCreateDatasource", ds);
super.setTargetDataSources(targetDataSources);
}
}
public List<Person> getAll() {
DynamicDataSource.key.put(Thread.currentThread(), "dataSource1")
log.info(" person getAll ")
return personMapper.getAll()
}