多数据源

多数据源处理,且自动切换数据源

1.配置数据源地址、账号、密码
#数据源 1
url:jdbc:mysql://ip1:3306/test1?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
driverClassName:com.mysql.jdbc.Driver
username:root
password:root

#数据源 2
url2:jdbc:mysql://ip2:3306/test2?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 
driverClassName2:com.mysql.jdbc.Driver
username2:root
password2:root
2.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.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context.xsd
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx.xsd
	">

	<!--配置整合mybatis过程-->


	<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

	<!--2、 数据源druid -->
	<!-- 数据源1 start -->
	<bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<!-- 数据库基本信息配置 -->
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<property name="driverClassName" value="${driverClassName}" />
		
	</bean>
	<!-- 数据源1 end -->

	<!-- 数据源2 start -->
	<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="url" value="${url2}" />
		<property name="username" value="${username2}" />
		<property name="password" value="${password2}" />
		<property name="driverClassName" value="${driverClassName2}" />
	</bean>
	<!-- 数据源2 end -->


	<bean id="dynamicDataSource" class="com.muke.datasource.DynamicDataSource">
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry key="key1" value-ref="dataSource1"/>
				<entry key="key2" value-ref="dataSource2"/>
			</map>
		</property>
		<!--默认数据源-->
		<property name="defaultTargetDataSource" ref="dataSource1"/>
	</bean>

	<!--3、 配置SqlSessionFactory对象 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 注入数据库连接池 -->
		<property name="dataSource" ref="dynamicDataSource"/>
		<!-- 配置mybatis全局配置文件:mybatis-config.xml -->
		<property name="configLocation" value="classpath:spring/mybatis-config.xml"/>
		<property name="typeAliasesPackage" value="com.muke.dto"/>
		<!-- 扫描sql配置文件:mapper需要的xml文件 -->
		<property name="mapperLocations" value="classpath:mapper/**/*.xml"></property>
		<!--  -->
		<!--  -->
	</bean>

	<!--4、配置扫描Dao接口包,动态实现DAO接口,注入到spring容器-->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!--注入SqlSessionFactory-->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
		<!-- 给出需要扫描的Dao接口-->
		<property name="basePackage" value="com.muke.dao.infirmary,com.muke.dao.local"/>
	</bean>

	<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dynamicDataSource"></property>
	</bean>
</beans>

3.数据源切换工具类
  • (1).枚举类
package com.muke.datasource;

/**
 * @author muke
 * @date 2019/9/1 18:21
 */
public enum DataSourceEnum {

    DS1("key1"), DS2("key2");

    private String key;

    DataSourceEnum(String key) { this.key = key; }

    public String getKey() { return key; }

    public void setKey(String key) {  this.key = key; }
}

  • (2).创建DynamicDataSourceHolder用于持有当前线程中使用的数据源标识
package com.muke.datasource;

/**
 * @author muke
 * @date 2019/8/21 16:58
 * DynamicDataSourceHolder用于持有当前线程中使用的数据源标识
 */
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();
    }

    public static void clearDataSourceKey() {
        dataSources.remove();
    }
}

  • (3).创建DynamicDataSource的类,继承AbstractRoutingDataSource并重写determineCurrentLookupKey方法
package com.muke.datasource;

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

/**
 * @author muke
 * @date 2019/8/21 16:56
 * DynamicDataSource的类,继承AbstractRoutingDataSource并重写determineCurrentLookupKey方法
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSources();
    }
}

4.(检测)手动切换数据源到这一步,已经可以试用各个数据源了,只需要在Service中查询前,调用一下即可
@Override
public TeacherVO getVOById(Integer id) {
   //切换数据源
    DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
    return teacherDao.getVOById(id);
}

@Override
public Product getPOById(Integer id) {
    //切换数据源
    DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
    return productDao.getPOById(id);
5.自动切换数据源(做此步骤必须要达到手动的切换的配置)
  • (1).虽然可以手动切换数据源,但每个方法都切换太过麻烦,很容易忘记,所以可以利用AOP,进行自动切换数据源
    创建切面类DataSourceExchange,切面的规则可以自定义,根据自己的项目做自己的规则,我这边是demo,我是从dao层切换的,dao下面有两个包,infirmary是主要源,local是第二数据源,第一源是默认源,如果调用第二源时需要切换
package com.muke.datasource;

import org.aspectj.lang.JoinPoint;

/**
 * @author muke
 * @date 2019/9/1 17:37
 */
public class DataSourceExchange {

    public void before(JoinPoint point) {

        System.out.println("切换了数据源");
        DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
    }

    /**
     * 执行后将数据源置为空
     */
    public void after() {

        System.out.println("清除数据源--------------------------");
        DataSourceHolder.clearDataSourceKey();
    }

    /**
     * @param joinPoint
     * @param ex
     * 针对当前拦截的切点方法中出现异常时所做的处理
     */
    public void afterThrow(JoinPoint joinPoint, Exception ex) {
        DataSourceHolder.clearDataSourceKey();
    }

}

  • (2).配置切面
<bean id="dataSourceExchange" class="com.muke.datasource.DataSourceExchange"/>
	<aop:config>
		<aop:aspect ref="dataSourceExchange">
			<aop:pointcut id="dataSourcePointcut" expression="execution(* com.muke.dao.local.*.*(..)))"/>
			<aop:before pointcut-ref="dataSourcePointcut" method="before"/>
			<aop:after pointcut-ref="dataSourcePointcut" method="after"/>
			<aop:after-throwing method="afterThrow" pointcut-ref="dataSourcePointcut" throwing="ex" />
		</aop:aspect>
	</aop:config>
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值