在spring中配置多个数据源,并实现动态切换
在spring中配置多个数据源,并实现动态切换
朋友遇到的问题,整理好了,我觉得不错,贴出来分享下。
spring中xml文件中的配置:
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass"><value>oracle.jdbc.driver.OracleDriver</value></property> <property name="jdbcUrl"><value>jdbc:oracle:thin:@127.0.0.1:1521:ORACLE</value></property> <property name="user"><value>htctposp</value></property> <property name="password"><value>htctposp</value></property> <property name="minPoolSize"><value>1</value></property> <property name="maxPoolSize"><value>5</value></property> <property name="maxIdleTime"><value>1800</value></property> </bean> <bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/mysql?characterEncoding=UTF8"></property> <property name="username" value="root"></property> <property name="password" value="1111"></property> </bean> <bean id="dataSource" class="com.huateng.util.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="dataSource1" value-ref="dataSource1"/> <entry key="dataSource2" value-ref="dataSource2"/> </map> </property> <property name="defaultTargetDataSource" ref="dataSource1"/> </bean>
写两个工具类DbContextHolder和DynamicDataSource,如下:
public class DynamicDataSource extends AbstractRoutingDataSource{ static Logger log=Logger.getLogger("DynamicDataSource"); /* (non-Javadoc) * @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey() */ protected Object determineCurrentLookupKey() { // DbContextHolder.setDbType("2"); return DbContextHolder.getDbType(); } }
public class DbContextHolder { private static final ThreadLocal contextHolder = new ThreadLocal(); public static void setDbType(String dbType){ contextHolder.set(dbType); } public static String getDbType(){ return (String)contextHolder.get(); } public static void clearDbType(){ contextHolder.remove(); } }
一般在调用service层之前就要切换数据库(一般要在action中),切换数据库的代码:
DbContextHolder.setDbType("dataSource2");
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30