后端使用數(shù)據(jù)庫提供服務(wù)時捞附,遇到性能問題鼠次,有時會采用分庫分表的方式(當然可以用ES集群代替?zhèn)鹘y(tǒng)DB)來降低單臺服務(wù)器壓力胚泌,提高整體吞吐量葡粒。而分庫就會有多數(shù)據(jù)源的問題瘟则,下面舉例說明下在Spring4 + MyBatis3的情況下黎炉,如何連接多個數(shù)據(jù)庫。
1.配置數(shù)據(jù)庫屬性文件db.properties(針對dbcp連接池)
initialSize=20
maxActive=200
maxIdle=20
minIdle=1
maxWait=60000
data1.driver=com.mysql.jdbc.Driver
data1.url=jdbc:mysql://localhsot:3306/test
data1.username=test
data1.password=123456
data2.driver=com.mysql.jdbc.Driver
data2.url=jdbc:mysql://localhsot:3307/test
data2.username=test
data2.password=123456
2.Spring配置文件(重點dynamicDataSource醋拧,事務(wù)采用攔截器方式慷嗜,并支持@Transcational注解方式)
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 數(shù)據(jù)源1:dataSource1-->
<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${data1.driver}" />
<property name="url" value="${data1.url}" />
<property name="username" value="${data1.username}" />
<property name="password" value="${data1.password}" />
<!-- 初始化連接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 連接池最大數(shù)量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 連接池最大空閑 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 連接池最小空閑 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 獲取連接最大等待時間 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- 數(shù)據(jù)源2:dataSource2-->
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${data2.driver}" />
<property name="url" value="${data2.url}" />
<property name="username" value="${data2.username}" />
<property name="password" value="${data2.password}" />
<!-- 初始化連接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 連接池最大數(shù)量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 連接池最大空閑 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 連接池最小空閑 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 獲取連接最大等待時間 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- 多數(shù)據(jù)源bean創(chuàng)建 -->
<bean id="dynamicDataSource" class="com.baidu.utils.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- 指定lookupKey和與之對應(yīng)的數(shù)據(jù)源 -->
<entry key="dataSource" value-ref="dataSource"></entry>
<entry key="dataSource2" value-ref="dataSource2"></entry>
</map>
</property>
<!-- 這里可以指定默認的數(shù)據(jù)源 -->
<property name="defaultTargetDataSource" ref="dataSource" />
</bean>
<!-- 自動掃描mapping.xml文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="dataSource" ref="dynamicDataSource" />
<property name="mapperLocations" value="classpath:com/baidu/mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring會自動查找其下的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--basePackage指定要掃描的包丹壕,在此包之下的映射器都會被搜索到庆械。 可指定多個包,包與包之間用逗號或分號分隔 -->
<property name="basePackage" value="com.baidu.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事務(wù)管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dynamicDataSource" />
</bean>
<!--聲明式事務(wù)配置-->
<tx:annotation-driven transaction-manager="txManager" />
<!--需要掃描的包-->
<context:component-scan base-package="com.baidu" />
<!-- 攔截器方式配置事務(wù) -->
<tx:advice id="transactionAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" propagation="NOT_SUPPORTED" />
<tx:method name="query*" propagation="NOT_SUPPORTED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.baidu.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
</beans>
3.實現(xiàn)DynamicDataSource類(需繼承AbstractRoutingDataSource菌赖;使用ThreadLocal保存當前線程連接設(shè)置缭乘,解決多線程相互干擾問題)
package com.baidu.utils;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();
public static void setDataSourceKey(String dataSource) {
dataSourceKey.set(dataSource);
}
@Override
protected Object determineCurrentLookupKey() {
return dataSourceKey.get();
}
}
4.調(diào)用示例
@Autowired
InvestorMapper investorMapper;
public List<Investor> queryInvestors(String epId) throws Exception {
/* 如果用dataSource1,則不需要調(diào)用setDataSource */
DynamicDataSource.setDataSource("dataSource2");
return investorMapper.queryInvestorsByEpId(epId);
}