web項目中配置多個數據源
spring + mybatis 多數據源配置有兩種解決方案
1、配置多個不同的數據源,使用一個sessionFactory,在業務邏輯使用的時候自動切換到不同的數據源, 有一個種是在攔截器里面根據不同的業務現切換到不同的datasource;
有的會在業務層根據業務來自動切換。
2、在spring項目中配置多個不同的數據源datasource,配置多個sqlSessionFactory,每個sqlSessionFactory對應一個datasource 在dao 層根據不同業務自行選擇使用哪個數據源的session來操作。使用請參考文章:http://blog.csdn.net/zhmz1326/article/details/52041918
具體講解方法1:
(一)配置
- <!-- 配置mysql -->
- <bean id="mysql_dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://127.0.0.1:3306/colleges" />
- <property name="username" value="root" />
- <property name="password" value="root" />
- </bean>
- <!-- 配置postgs -->
- <bean id="postgs_dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="org.postgresql.Driver" />
- <property name="url" value="jdbc:postgresql://114.215.83.3:5432/coges" />
- <property name="username" value="postgres" />
- <property name="password" value="postgres" />
- </bean>
- <!-- 配置動態數據源 -->
- <bean id ="dataSource" class= "com.mote.dc.changedb.DynamicDataSource" >
- <property name ="targetDataSources">
- <map key-type ="java.lang.String">
- <entry value-ref ="postgs_dataSource" key= "postgs_dataSource"></entry >
- <entry value-ref ="mysql_dataSource" key= "mysql_dataSource"></entry >
- </map >
- </property>
- <!-- 默認使用mysql -->
- <property name ="defaultTargetDataSource" ref= "mysql_dataSource"></property >
- </bean>
(二)創建數據源名稱常量類
- @SuppressWarnings("all")
- public class DataSourceType {
- public static final String SOURCE_MYSQL = "mysql_dataSource";
- public static final String SOURCE_POSTGS = "postgs_dataSource";
- }
(三)創建負責切換數據源的類
- public class DataSourceContextHolder {
- private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
- public static void setDbType(String dbType) {
- contextHolder.set(dbType);
- }
- public static String getDbType() {
- return ((String) contextHolder.get());
- }
- public static void clearDbType() {
- contextHolder.remove();
- }
- }
(四) 建立動態數據源類,該類必須繼承AbstractRoutingDataSource,且實現方法determineCurrentLookupKey
- import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
- public class DynamicDataSource extends AbstractRoutingDataSource{
- @Override
- protected Object determineCurrentLookupKey() {
- return DataSourceContextHolder. getDbType();
- }
- }
(五)當需要使用某個數據庫的時候,使用下面一行代碼進行切換
- //切換數據庫
- DataSourceContextHolder.setDbType(DataSourceType.SOURCE_POSTGS);
ok了
原文鏈接:http://blog.csdn.net/qq_37936542/article/details/78550424