javaweb項目配置多數據庫

項目結構:

配置文件:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
    xmlns:websocket="http://www.springframework.org/schema/websocket"
    xmlns:security="http://www.springframework.org/schema/security"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
        http://www.springframework.org/schema/security   
        http://www.springframework.org/schema/security/spring-security-3.2.xsd  
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/data/jpa   
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd  
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">  
    
    <!-- 數據庫配置文件位置 -->  
    <context:property-placeholder location="classpath:/jdbc.properties" />  
    <context:component-scan base-package="com.cn" /> 
    
    <!-- 配置c3p0數據源 -->  
    <bean id="parentDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="user" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}" />
		<property name="initialPoolSize" value="${c3p0.initialPoolSize}" />
		<property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
		<property name="minPoolSize" value="${c3p0.minPoolSize}" />
		<property name="maxStatements" value="${c3p0.maxStatements}" />
		<property name="testConnectionOnCheckin" value="false" />
		<property name="acquireRetryAttempts" value="5" />
		<property name="acquireRetryDelay" value="2000" />
		<property name="breakAfterAcquireFailure" value="false" />
	</bean>  
  	
  	<bean id="localDataSource" parent="parentDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"></property>
    </bean>
    <bean id="cnccDataSource" parent="parentDataSource">
        <property name="jdbcUrl" value="${jdbc.url1}"></property>
    </bean>
  	
  	<bean id="dataSource" class="com.cn.dynamicDS.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry value-ref="localDataSource" key="local"></entry>
                <entry value-ref="cnccDataSource" key="cncc"></entry>
            </map>
        </property>
        <property name="defaultTargetDataSource" ref="cnccDataSource"></property>
    </bean>
  
    <!-- 使用JDBC事物 -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
	<!-- 使用annotation註解方式配置事務   -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
  
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> 
    </bean>  
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg index="0" ref="sqlSessionFactory" />  
    </bean>

</beans>  
jdbc.properties:

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:實例名
jdbc.username=用戶名
jdbc.password=密碼
jdbc.url1=jdbc:oracle:thin:@192.168.42.147:1521:第二個數據庫實例名
#也可配置其他數據庫

c3p0.initialPoolSize=10
c3p0.maxPoolSize=10
c3p0.minPoolSize=10
c3p0.maxStatements=10
常量類:

package com.cn.cncc.dynamicDS;

/**
 * 常量類
 * @author hjr
 *
 */
public class DataSourceConst {
	/*
	 * 操作本地數據庫
	 */
    public static final String LOCAL = "local";
    /*
     * 操作BMC遠端數據庫
     */
    public static final String CNCC = "cncc";
}
動態數據源:

package com.cn.cncc.dynamicDS;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 動態數據源
 * @author hjr
 *
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        // TODO Auto-generated method stub
        return DataSourceContextHolder.getDataSourceType();
    }

}
數據源動態切換方法類:

package com.cn.cncc.dynamicDS;

/**
 * 數據源切換方法類
 * @author hjr
 *
 */
public class DataSourceContextHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();//線程本地環境
    
    //設置數據源類型
    public static void  setDataSourceType(String dataSourceType)
    {
        contextHolder.set(dataSourceType);
    }
    
    //獲取數據源類型
    public static String getDataSourceType()
    {
        return contextHolder.get();
    }
    
    //清除數據源類型
    public static void clearDataSourceType()
    {
        contextHolder.remove();
    }
}
測試類:
package test;

import java.io.BufferedReader;
import java.math.BigDecimal;
import java.sql.Clob;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cn.cncc.dynamicDS.DataSourceConst;
import com.cn.cncc.dynamicDS.DataSourceContextHolder;
import com.cn.cncc.service.CpuService;



public class dyanmicDataSourceTest {
	
    
	Logger log = Logger.getLogger(dyanmicDataSourceTest.class);

    private CpuService cpuServiceImpl;

	@Before
	public void before(){
		
		ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext-servlet.xml","classpath:applicationContext.xml"});

		cpuServiceImpl = (CpuService)context.getBean("cpuServiceImpl");

	}
	
	@Test
	public void cpuTest(){
		String dataSourceType = DataSourceContextHolder.getDataSourceType();//當前數據庫
		System.out.println(dataSourceType);
		List<Object> findcpu = cpuServiceImpl.findCpuTop5();
		if(null != findcpu && findcpu.size()>0){
			try {
				DataSourceContextHolder.setDataSourceType(DataSourceConst.LOCAL);//切換數據庫
				int insertcpu = cpuServiceImpl.insertCpuTop5(findcpu);//在另一個數據庫查詢
				String dataSourceType2 = DataSourceContextHolder.getDataSourceType();
				System.out.println(dataSourceType2);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章