c3p0如何配置多数据源的解决方法
来源:互联网 发布:讲你知有没有国语 编辑:程序博客网 时间:2024/06/06 14:00
c3p0如何配置多数据源的解决方法
一、问题描述:
项目开发时,用c3p0管理数据连接。但是项目需要动态连接两个以上的数据库,如何用c3p0配置多数据源。
二、解决方法:
使用c3p0结合spring提供的数据源路由(DataSource Routing)对象,该对象构造了一个存储多数据源的Map,可以根据指定的key动态的查找对应的数据源。
具体实现如下:
1.编写c3p0配置:
-
- <bean id="parentDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
- <property name="driverClass">
- <value>${jdbc.driverClassName}</value>
- </property>
-
-
- <property name="acquireIncrement" value="5"/>
-
-
- <property name="initialPoolSize" value="3"/>
-
- <property name="minPoolSize" value="1"/>
-
- <property name="maxPoolSize" value="20"/>
-
-
- <property name="acquireRetryAttempts" value="30"/>
-
-
- <property name="checkoutTimeout" value="18000"/>
-
-
- <property name="idleConnectionTestPeriod" value="1200"/>
-
-
- <property name="maxIdleTime" value="1800"/>
-
-
- <property name="testConnectionOnCheckin" value="true"/>
- </bean>
2.数据源配置:-
- <bean id="fromDataSource" parent="parentDataSource">
- <property name="jdbcUrl">
- <value>${jdbc.from.url}</value>
- </property>
- <property name="user">
- <value>${jdbc.from.username}</value>
- </property>
- <property name="password">
- <value>${jdbc.from.password}</value>
- </property>
- </bean>
- <bean id="toDataSource" parent="parentDataSource">
- <property name="jdbcUrl">
- <value>${jdbc.to.url}</value>
- </property>
- <property name="user">
- <value>${jdbc.to.username}</value>
- </property>
- <property name="password">
- <value>${jdbc.to.password}</value>
- </property>
- </bean>
3.动态数据源加载配置:-
- <bean id="dynamicDataSource" class="com.shxt.power.util.DynamicDataSource">
- <property name="targetDataSources">
- <map key-type="java.lang.String">
- <entry key="fromDataSource" value-ref="fromDataSource"/>
- <entry key="toDataSource" value-ref="toDataSource"/>
- </map>
- </property>
- <property name="defaultTargetDataSource" ref="fromDataSource"/>
- </bean>
4.实现spring的数据源路由对象:- import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
-
- public class DynamicDataSource extends AbstractRoutingDataSource {
-
- @Override
- protected Object determineCurrentLookupKey() {
- String sourceType = CustomContextHolder.getCustomerType();
-
- return sourceType;
- }
- }
5.编写自定义的数据源key:- public class CustomContextHolder {
- private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
- public static final String DATA_SOURCE_FROM = "fromDataSource";
- public static final String DATA_SOURCE_TO = "toDataSource";
-
- public static void setCustomerType(String customerType) {
- contextHolder.set(customerType);
- }
-
- public static String getCustomerType() {
- return contextHolder.get();
- }
-
- public static void clearCustomerType() {
- contextHolder.remove();
- }
- }