- 配置數(shù)據(jù)源地址、賬號(hào)、密碼
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url1=jdbc:mysql://ip1:3306/easywork?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username1=xxx
jdbc.password1=xxx!
jdbc.url2=jdbc:mysql://ip2:3306/easywork?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username2=xxx
jdbc.password2=xxx
druid.pool.size.max=20
druid.pool.size.min=3
druid.pool.size.init=3
- xml中配置數(shù)據(jù)源
<!--配置整合mybatis過(guò)程-->
<!--1、配置數(shù)據(jù)庫(kù)相關(guān)參數(shù)-->
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
<!--2、 數(shù)據(jù)源druid -->
<!-- 數(shù)據(jù)源1 start -->
<bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url1}"/>
<property name="username" value="${jdbc.username1}"/>
<property name="password" value="${jdbc.password1}"/>
<!-- 設(shè)置初始大小、最小、最大 連接數(shù)-->
<property name="initialSize" value="${druid.pool.size.init}"/>
<property name="minIdle" value="${druid.pool.size.min}"/>
<property name="maxActive" value="${druid.pool.size.max}"/>
<!-- 配置監(jiān)控統(tǒng)計(jì)攔截的filters,wall用于防止sql注入,stat用于統(tǒng)計(jì)分析 -->
<property name="filters" value="wall,stat" />
</bean>
<!-- 數(shù)據(jù)源1 end -->
<!-- 數(shù)據(jù)源2 start -->
<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url2}"/>
<property name="username" value="${jdbc.username2}"/>
<property name="password" value="${jdbc.password2}"/>
<!-- 設(shè)置初始大小、最小、最大 連接數(shù)-->
<property name="initialSize" value="${druid.pool.size.init}"/>
<property name="minIdle" value="${druid.pool.size.min}"/>
<property name="maxActive" value="${druid.pool.size.max}"/>
<!-- 配置監(jiān)控統(tǒng)計(jì)攔截的filters,wall用于防止sql注入,stat用于統(tǒng)計(jì)分析 -->
<property name="filters" value="wall,stat" />
</bean>
<!-- 數(shù)據(jù)源2 end -->
<bean id="dynamicDataSource" class="com.gs.dataSource.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="ds1" value-ref="dataSource1"/>
<entry key="ds2" value-ref="dataSource2"/>
</map>
</property>
<!--默認(rèn)數(shù)據(jù)源-->
<property name="defaultTargetDataSource" ref="dataSource2"/>
</bean>
<!--3、 配置SqlSessionFactory對(duì)象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入數(shù)據(jù)庫(kù)連接池 -->
<property name="dataSource" ref="dynamicDataSource"/>
<!-- 配置mybatis全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 掃描entitys包,使用別名;隔開 -->
<!-- TODO 不能使用通配 但是可以直接指定到 com.trjn.lowsmanage 試了一下 加載速度沒(méi)有影響 -->
<property name="typeAliasesPackage" value="com.gs"/>
<!-- 掃描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/**/*.xml"></property>
<!-- -->
<!-- -->
</bean>
<!--4、配置掃描Dao接口包,動(dòng)態(tài)實(shí)現(xiàn)DAO接口,注入到spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描的Dao接口-->
<property name="basePackage" value="com.gs.**.dao"/>
</bean>
- 數(shù)據(jù)源切換工具類
枚舉類
public enum DataSourceEnum {
DS1("ds1"), DS2("ds2");
private String key;
DataSourceEnum(String key) { this.key = key; }
public String getKey() { return key; }
public void setKey(String key) { this.key = key; }
}
創(chuàng)建DynamicDataSourceHolder用于持有當(dāng)前線程中使用的數(shù)據(jù)源標(biāo)識(shí)
/**
* DynamicDataSourceHolder用于持有當(dāng)前線程中使用的數(shù)據(jù)源標(biāo)識(shí)
*/
public class DataSourceHolder {
private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();
public static void setDataSources(String dataSource) {
dataSources.set(dataSource);
}
public static String getDataSources() {
return dataSources.get();
}
}
創(chuàng)建DynamicDataSource的類,繼承AbstractRoutingDataSource并重寫determineCurrentLookupKey方法
/**
* DynamicDataSource的類,繼承AbstractRoutingDataSource并重寫determineCurrentLookupKey方法
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceHolder.getDataSources();
}
}
- 手動(dòng)切換數(shù)據(jù)源
到這一步,已經(jīng)可以試用各個(gè)數(shù)據(jù)源了,只需要在Service中查詢前,調(diào)用一下即可
//teacherService
@Override
public TeacherVO getVOById(Integer id) {
DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
return teacherDao.getVOById(id);
}
//productService
@Override
public Product getPOById(Integer id) {
DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
return productDao.getPOById(id);
}
此時(shí),兩個(gè)方法分別從不同的數(shù)據(jù)源中查詢數(shù)據(jù)
- 自動(dòng)切換數(shù)據(jù)源
雖然可以手動(dòng)切換數(shù)據(jù)源,但每個(gè)方法都切換太過(guò)麻煩,很容易忘記,所以可以利用AOP,進(jìn)行自動(dòng)切換數(shù)據(jù)源
創(chuàng)建切面類DataSourceExchange,切面的規(guī)則可以自定義,根據(jù)自己的項(xiàng)目做自己的規(guī)則,我這邊是demo,所以product、teacher包分別用不同的數(shù)據(jù)源。
public class DataSourceExchange {
public void before(JoinPoint point) {
//獲取目標(biāo)對(duì)象的類類型
Class<?> aClass = point.getTarget().getClass();
String c = aClass.getName();
String[] ss = c.split("\\.");
//獲取包名用于區(qū)分不同數(shù)據(jù)源
String packageName = ss[2];
if ("product".equals(packageName)) {
DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
System.out.println("數(shù)據(jù)源:"+DataSourceEnum.DS2.getKey());
} else {
DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
System.out.println("數(shù)據(jù)源:"+DataSourceEnum.DS1.getKey());
}
}
/**
* 執(zhí)行后將數(shù)據(jù)源置為空
*/
public void after() {
DataSourceHolder.setDataSources(null);
}
}
配置切面
<bean id="dataSourceExchange" class="com.gs.aop.DataSourceExchange"/>
<aop:config>
<aop:aspect ref="dataSourceExchange">
<aop:pointcut id="dataSourcePointcut" expression="execution(* com.gs.**.service.impl.*ServiceImpl.*(..))"/>
<aop:before pointcut-ref="dataSourcePointcut" method="before"/>
<aop:after pointcut-ref="dataSourcePointcut" method="after"/>
</aop:aspect>
</aop:config>
這樣,在調(diào)用service方法時(shí)就會(huì)自動(dòng)切換數(shù)據(jù)源了