多数据源的实现,这里就来个实例吧

1、在 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"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
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/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"> <!-- 加载配置属性文件 -->
<context:property-placeholder
ignore-unresolvable="true" location="classpath:conf.properties" />
<!-- C3P0连接池配置 -->
<bean id="dataSource_zh_CN" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${db1.jdbc.driver}" />
<property name="jdbcUrl" value="${db1.jdbc.url}" />
<property name="user" value="${db1.jdbc.username}" />
<property name="password" value="${db1.jdbc.password}" /> <!-- 配置初始化大小、最小、最大 -->
<property name="initialPoolSize" value="${jdbc.pool.init}" />
<property name="minPoolSize" value="${jdbc.pool.minIdle}" />
<property name="maxPoolSize" value="${jdbc.pool.maxActive}" />
<property name="maxIdleTime" value="60000" />
</bean> <!-- C3P0连接池配置 -->
<bean id="dataSource_en_US" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${db2.jdbc.driver}" />
<property name="jdbcUrl" value="${db2.jdbc.url}" />
<property name="user" value="${db2.jdbc.username}" />
<property name="password" value="${db2.jdbc.password}" /> <!-- 配置初始化大小、最小、最大 -->
<property name="initialPoolSize" value="${jdbc.pool.init}" />
<property name="minPoolSize" value="${jdbc.pool.minIdle}" />
<property name="maxPoolSize" value="${jdbc.pool.maxActive}" />
<property name="maxIdleTime" value="60000" />
</bean> <bean id="dataSource" class="com.bkc.bpmp.core.datasource.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="dataSource_zh_CN" value-ref="dataSource_zh_CN" />
<entry key="dataSource_en_US" value-ref="dataSource_en_US" />
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSource_zh_CN" />
</bean> </beans>

  

2、在 Spring 配置文件中配置 AOP 切面信息,当访问 包 com.bkc.bpmp 及下面的子包中的类的方法时

<!-- 开启aop注解方式 -->
<aop:aspectj-autoproxy proxy-target-class="false"/> <bean id="dataSourceInterceptor" class="com.bkc.bpmp.core.aspectj.DataSourceInterceptor" /> <aop:config>
<aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">
<aop:pointcut id="setDs" expression="execution(* com.bkc.bpmp..*.*(..))" />
<aop:before method="setdataSourceCnOrEn" pointcut-ref="setDs"/>
</aop:aspect>
</aop:config>

3、实现 数据源 切面切换的方法,这里假设是根据 locale 来切换数据源的

package com.bkc.bpmp.core.aspectj;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder; import com.bkc.bpmp.core.annotation.DbType;
import com.bkc.bpmp.core.contants.DbTypeEnum;
import com.bkc.bpmp.core.datasource.DatabaseContextHolder; /**
* 用于实现 动态数据库切换的AOP 方法类
*
* @author ppnie
*/
public class DataSourceInterceptor
{
/**
* 设置数据源为中文 还是 英文
* @param jp
*/
public void setdataSourceCnOrEn(JoinPoint jp) { String curLocale = LocaleContextHolder.getLocale().toString();
System.out.println("==================dataSource_"+curLocale);
if(curLocale.equals("en_US"))
{
DatabaseContextHolder.setCustomerType("dataSource_"+curLocale);
}
else
{
DatabaseContextHolder.setCustomerType("dataSource_zh_CN");
}
logger.info("======="+"dataSource_"+curLocale+"======="); }
}

4、自定义动态数据源的切换方法,主要就是 写一个 AbstractRoutingDataSource 的子类啦

package com.bkc.bpmp.core.datasource;

public class DatabaseContextHolder
{ private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setCustomerType(String customerType)
{
contextHolder.set(customerType);
} public static String getCustomerType()
{
return contextHolder.get();
} public static void clearCustomerType()
{
contextHolder.remove();
}
}

  

package com.bkc.bpmp.core.datasource;

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

public class DynamicDataSource extends AbstractRoutingDataSource
{ @Override
protected Object determineCurrentLookupKey()
{
return DatabaseContextHolder.getCustomerType();
} }

  

 就这样,达到触发条件的时候,就会去切换数据库啦

使用AOP 实现多数据源 切换的更多相关文章

  1. 【原】继承AbstractRoutingDataSource再通过AOP实现动态数据源切换

    关于AbstractRoutingDataSource动态切换数据源是我在研究某开源项目时候才注意到的,大概就看懂了Spring AOP切面这里,根据作者的意思是通过继承这个抽象类可以实现数据源的动态 ...

  2. 继承AbstractRoutingDataSource再通过AOP实现动态数据源切换

    package com.zdd.data.aspect; import java.util.ArrayList; import java.util.HashMap; import java.util. ...

  3. 继承AbstractRoutingDataSource再通过AOP实现动态数据源切换(转)

    关于AbstractRoutingDataSource我在研究开源中国的开源项目时候才发现,好奇的看了一下代码发现自己看不明白,大概就看懂了Spring AOP切面这里,根据注释作者的意思是通过这个可 ...

  4. 【开发笔记】- AbstractRoutingDataSource动态数据源切换,AOP实现动态数据源切换

    AbstractRoutingDataSource动态数据源切换 上周末,室友通宵达旦的敲代码处理他的多数据源的问题,搞的非常的紧张,也和我聊了聊天,大概的了解了他的业务的需求.一般的情况下我们都是使 ...

  5. AbstractRoutingDataSource动态数据源切换,AOP实现动态数据源切换

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/u012881904/article/de ...

  6. Java:基于AOP的动态数据源切换(附源码)

    1 动态数据源的必要性 我们知道,物理服务机的CPU.内存.存储空间.连接数等资源都是有限的,某个时段大量连接同时执行操作,会导致数据库在处理上遇到性能瓶颈.而在复杂的互联网业务场景下,系统流量日益膨 ...

  7. Spring主从数据库的配置和动态数据源切换原理

    原文:https://www.liaoxuefeng.com/article/00151054582348974482c20f7d8431ead5bc32b30354705000 在大型应用程序中,配 ...

  8. SpringBoot31 整合SpringJDBC、整合MyBatis、利用AOP实现多数据源

    一.整合SpringJDBC 1  JDBC JDBC(Java Data Base Connectivity,Java 数据库连接)是一种用于执行 SQL 语句的 Java API,可以为多种关系数 ...

  9. dubbo服务+Spring事务+AOP动态数据源切换 出错

    1:问题描述,以及分析 项目用了spring数据源动态切换,服务用的是dubbo.在运行一段时间后程序异常,更新操作没有切换到主库上. 这个问题在先调用读操作后再调用写操作会出现. 经日志分析原因: ...

随机推荐

  1. IT菜鸟的第一天

    小弟愚钝,被别人影响,打算入IT行业试试水的深浅,俗话说技不压身,多会一种就多一条路子,抱着这种求知的心态我就开始的我在汉企的IT生涯! 第一天无非就是简介,对IT行业的介绍,反正听得我挺懵的,不过介 ...

  2. ThreadLocal用法和实现原理

    如果你定义了一个单实例的java bean,它有若干属性,但是有一个属性不是线程安全的,比如说HashMap.并且碰巧你并不需要在不同的线程中共享这个属性,也就是说这个属性不存在跨线程的意义.那么你不 ...

  3. AccessHelper 需修改

    using System; using System.Collections.Generic; using System.Configuration; using System.Data; using ...

  4. 10 Things Every Java Programmer Should Know about String

    String in Java is very special class and most frequently used class as well. There are lot many thin ...

  5. Types of intraclass correlation coefficience (ICC)

    Reference: Andellini M, Cannatà V, Gazzellini S, et al. Test-retest reliability of graph metrics of ...

  6. windows Server 2008各版本区别详解

    Windows Server 2008 是专为强化下一代网络.应用程序和 Web 服务的功能而设计,是有史以来最先进的 Windows Server 操作系统.拥有 Windows Server 20 ...

  7. JAVA CDI 学习(5) - 如何向RESTFul Service中注入EJB实例

    RESTFul Service中如果要注入EJB实例,常规的@Inject将不起作用,在Jboss中,应用甚至都启动不起来(因为@Inject注入失败),解决方法很简单:将@Inject换成@EJB ...

  8. .clear 万能清除浮动

    html body div.clear, html body span.clear { background: none; border: 0; clear: both; display: block ...

  9. Theano2.1.16-基础知识之调试:常见的问题解答

    来自:http://deeplearning.net/software/theano/tutorial/shape_info.html Debugging Theano: FAQ and Troubl ...

  10. HoloLens开发手记 - 应用程序模型 App model

    HoloLens使用Universal Windows Platform (UWP)提供的应用模型.UWP应用模型定义了应用如何被安全和完全地安装.更新.版本控制和移除.它管理了应用生命周期 - 应用 ...