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();
			}
		}
	}
	
	
}





  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值