Druid 配多个数据库

hibernateConfig.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
	<!-- 配置数据源 -->
	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<property name="url" value="${MessagePush.jdbc_url}" />
		<property name="username" value="${MessagePush.jdbc_username}" />
		<property name="password" value="${MessagePush.jdbc_password}" />
		<!-- 初始化连接大小 -->
		<property name="initialSize" value="0" />
		<!-- 连接池最大使用连接数量 -->
		<property name="maxActive" value="${MessagePush.jdbc_maxActive}" />
		<!-- 连接池最大空闲 -->
		<!--<property name="maxIdle" value="20" /> -->
		<!-- 连接池最小空闲 -->
		<property name="minIdle" value="0" />
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="60000" />
		<!-- <property name="poolPreparedStatements" value="true" /> <property 
			name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->

		<property name="validationQuery" value="${MessagePush.validationQuery}" />
		<property name="testOnBorrow" value="true" />
		<property name="testOnReturn" value="true" />
		<property name="testWhileIdle" value="true" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="25200000" />
		<!-- 打开removeAbandoned功能 -->
		<property name="removeAbandoned" value="true" />
		<!-- 1800秒,也就是30分钟 -->
		<property name="removeAbandonedTimeout" value="1800" />
		<!-- 关闭abanded连接时输出错误日志 -->
		<property name="logAbandoned" value="true" />
		<!-- 监控数据库 -->
		<!-- <property name="filters" value="stat" /> -->
		<property name="filters" value="mergeStat" />
	</bean>
	<bean name="dataSource1" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<property name="url" value="${MessagePush.jdbc_url1}" />
		<property name="username" value="${MessagePush.jdbc_username1}" />
		<property name="password" value="${MessagePush.jdbc_password1}" />
		<!-- 初始化连接大小 -->
		<property name="initialSize" value="0" />
		<!-- 连接池最大使用连接数量 -->
		<property name="maxActive" value="${MessagePush.jdbc_maxActive1}" />
		<!-- 连接池最大空闲 -->
		<!--<property name="maxIdle" value="20" /> -->
		<!-- 连接池最小空闲 -->
		<property name="minIdle" value="0" />
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="60000" />
		<!-- <property name="poolPreparedStatements" value="true" /> <property 
			name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->

		<property name="validationQuery" value="${MessagePush.validationQuery1}" />
		<property name="testOnBorrow" value="true" />
		<property name="testOnReturn" value="true" />
		<property name="testWhileIdle" value="true" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="25200000" />
		<!-- 打开removeAbandoned功能 -->
		<property name="removeAbandoned" value="true" />
		<!-- 1800秒,也就是30分钟 -->
		<property name="removeAbandonedTimeout" value="1800" />
		<!-- 关闭abanded连接时输出错误日志 -->
		<property name="logAbandoned" value="true" />
		<!-- 监控数据库 -->
		<!-- <property name="filters" value="stat" /> -->
		<property name="filters" value="mergeStat" />
	</bean>

	<bean id="dataSourceBu"
		class="com.roi.patrol.datasources.ThreadLocalRountingDataSource">
		<property name="defaultTargetDataSource" ref="dataSource" />
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry key="DATASOURCE1" value-ref="dataSource1" />
				<entry key="DATASOURCE" value-ref="dataSource" />
				<!-- 这里还可以加多个dataSource -->
			</map>
		</property>
	</bean>

	<!-- 配置hibernate session工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSourceBu" />
		<property name="hibernateProperties">
			<props>
				<prop key="javax.persistence.validation.mode">${MessagePush.javax.persistence.validation.mode}
				</prop>
				<!-- web项目启动时是否更新表结构 -->
				<prop key="hibernate.hbm2ddl.auto">${MessagePush.hibernate.hbm2ddl.auto}</prop>
				<!-- 系统使用的数据库方言,也就是使用的数据库类型 -->
				<prop key="hibernate.dialect">${MessagePush.hibernate.dialect}</prop>
				<!-- 是否打印Hibernate生成的SQL到控制台 -->
				<prop key="hibernate.show_sql">${MessagePush.hibernate.show_sql}</prop>
				<!-- 是否格式化打印出来的SQL -->
				<prop key="hibernate.format_sql">${MessagePush.hibernate.format_sql}</prop>
				<prop key="hibernate.current_session_context_class">${MessagePush.hibernate.current_session_context_class}
				</prop>
				<!-- <prop key="hibernate.default_schema">${MessagePush.hibernate.default_schema}</prop> -->
			</props>
		</property>
		<!-- 自动扫描注解方式配置的hibernate类文件 -->
		<!-- <property name="packagesToScan"> <list> <value>com.roi.patrol.entity</value> 
			</list> </property> -->
		<property name="mappingLocations">
			<value>classpath:/com/roi/patrol/entity/**/mappings/*.hbm.xml</value>
		</property>
	</bean>

	<!-- 配置事务管理器 -->
	<bean name="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 注解方式配置事物 -->
	<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
	<!-- 拦截器方式配置事物 -->
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" />
			<!-- <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" 
				propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" 
				/> -->
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="merge*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="enable*" propagation="REQUIRED" />
			<tx:method name="disable*" propagation="REQUIRED" />
			<!-- <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" 
				propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED"/> -->
			<!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 -->
			<tx:method name="get*" propagation="REQUIRED" read-only="true" />
			<tx:method name="count*" propagation="REQUIRED" read-only="true" />
			<tx:method name="find*" propagation="REQUIRED" read-only="true" />
			<tx:method name="list*" propagation="REQUIRED" read-only="true" />
			<tx:method name="*" propagation="REQUIRED" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 切面,将事物用在哪些对象上 -->
	<aop:config>
		<aop:pointcut id="transactionPointcut"
			expression="execution(* com.roi.patrol.service.*.impl.*.*(..))" />
		<aop:advisor pointcut-ref="transactionPointcut"
			advice-ref="transactionAdvice" />
	</aop:config>

</beans>

config.properties 连接数据库配置文件

#The Base DB Config For H—MessagePush
MessagePush.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
MessagePush.driverClassName=com.mysql.jdbc.Driver
MessagePush.validationQuery=SELECT 1
#MessagePush.jdbc_url=jdbc:mysql://192.168.2.200:3306/roiac?useUnicode=true&amp;characterEncoding=UTF-8
MessagePush.jdbc_url=jdbc:mysql://120.76.222.174:3306/roiac?useUnicode=true&amp;characterEncoding=UTF-8
MessagePush.jdbc_username=root
#MessagePush.jdbc_password=123456
MessagePush.jdbc_password=css4995
MessagePush.jdbc_maxActive=50
MessagePush.hibernate.hbm2ddl.auto=none
#MessagePush.hibernate.default_schema=roiac
MessagePush.hibernate.show_sql=true
MessagePush.hibernate.format_sql=true
MessagePush.javax.persistence.validation.mode=none
MessagePush.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

####能源库
#The Base DB Config For H—MessagePush
MessagePush.driverClassName1=com.mysql.jdbc.Driver
MessagePush.validationQuery1=SELECT 1
#MessagePush.jdbc_url1=jdbc:mysql://192.168.2.200:3306/roiac?useUnicode=true&amp;characterEncoding=UTF-8
MessagePush.jdbc_url1=jdbc:mysql://120.76.222.174:3306/energy?useUnicode=true&amp;characterEncoding=UTF-8
MessagePush.jdbc_username1=root
#MessagePush.jdbc_password1=123456
MessagePush.jdbc_password1=css4995
MessagePush.jdbc_maxActive1=50

编写一个控制类

注意需要使用spring管理控制类的初始化操作 在spring的配置文件上加入,写控制类的地址

<?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:context="http://www.springframework.org/schema/context" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 ">
	<context:annotation-config />
 
    <!-- 引入属性文件,config.properties位于src/main/resources目录下 -->
    <context:property-placeholder location="config.properties" />
 
     <!-- 自动扫描dao和service包(自动注入) -->
    <context:component-scan base-package="com.roi.patrol.main.task,com.roi.patrol.service,com.roi.patrol.dao"  >
    </context:component-scan>
    
    <import resource="hibernateConfig.xml"/>

</beans>

控制类

package com.roi.patrol.datasources;

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

/**
 * @Copyright:Copyright (c) 2017 - 2066
 * @Company:湖南瑞翼能源股份有限公司
 * @Title:
 * @Description:
 * @Author:simon
 * @Since:2017年4月10日 下午4:09:14
 * @Version:1.1.0
 */
public class ThreadLocalRountingDataSource extends AbstractRoutingDataSource {

	@Override
	protected Object determineCurrentLookupKey() {
		return DataSourceTypeManager.get();
	}
	
}

DataSourceTypeManager 类的信息

package com.roi.patrol.datasources;

/**
 * @Copyright:Copyright (c) 2017 - 2066
 * @Company:湖南瑞翼能源股份有限公司
 * @Title:数据源管理类
 * @Description:通过 TheadLocal 来保存每个线程选择哪个数据源的标志(key)
 * @Author:simon
 * @Since:2017年4月10日 下午4:08:58
 * @Version:1.1.0
 */
public class DataSourceTypeManager {
	private static final ThreadLocal<String> dataSourceTypes = new ThreadLocal<String>();

	public static String get() {
		return dataSourceTypes.get();
	}

	public static void set(String dataSourceType) {
		dataSourceTypes.set(dataSourceType);
	}

	public static void clearDataSourceType() {
		dataSourceTypes.remove();
	}
}

设置手动操作

我们需要把之前连接数据库的连接方式设置成默认方式,那么之前的代码就可以不需要改变了。

//DataSourceInstances.SOURCE 配置的连接名称
DataSourceTypeManager.set(DataSourceInstances.SOURCE);

//如果操作完毕,最好切换到默认的。

转载于:https://my.oschina.net/u/2948232/blog/1477176

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值