public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static synchronized void setDbType(final String dbType) { contextHolder.set(dbType); } public static String getDbType() { return (contextHolder.get()); } public static void clearDbType() { contextHolder.remove(); } } import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDbType(); } }
<bean id="dataSource" class="DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <!-- <entry value-ref="dataSourceSpied" key="dataSourceSpied" /> --> <entry value-ref="dataSource1" key="dataSource1" /> <entry value-ref="dataSource2" key="dataSource2" /> </map> </property> <!-- 默认使用productDataSource的数据源 --> <property name="defaultTargetDataSource" ref="dataSource1" /> </bean>
<bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${druid.initialSize}" />
<property name="minIdle" value="${druid.minIdle}" />
<property name="maxActive" value="${druid.maxActive}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${druid.maxWait}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${druid.validationQuery}" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" />
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="${druid.filters}" />
</bean>
<bean id="dataSource2">
。。。。。。
</bean>
//调用之前设置 DataSourceContextHolder.setDbType("dataSource2"); List<Map> result = this.leakAnalysisService.getApfLeakData(param);