侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Spring AOP 动态多数据源的实例详解

技术  /  管理员 发布于 7年前   215

 Spring AOP 动态多数据源的实例详解

当项目中使用到读写分离的时候,我们就会遇到多数据源的问题。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring和Mybatis的框架的项目中,我们在spring配置中往往是配置一个dataSource来连接数据库,然后绑定给sessionFactory,在dao层代码中再指定sessionFactory来进行数据库操作。

 

正如上图所示,每一块都是指定绑死的,如果是多个数据源,也只能是下图中那种方式。

可看出在Dao层代码中写死了两个SessionFactory,这样日后如果再多一个数据源,还要改代码添加一个SessionFactory,显然这并不符合开闭原则。

那么正确的做法应该是:

具体代码与配置如下:

1、applicationContext-mgr.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"  xmlns:p="http://www.springframework.org/schema/p"  xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  <!-- use annotation -->  <context:annotation-config />    <context:component-scan base-package="com.carl.o2o.**.mgr">  </context:component-scan>  <!-- master -->  <bean id="master" class="com.mchange.v2.c3p0.ComboPooledDataSource">    <property name="driverClass" value="${driverClassName_master}"/>    <property name="user" value="${username_master}"/>    <property name="password" value="${password_master}"/>    <property name="jdbcUrl" value="${url_master}?Unicode=true&characterEncoding=UTF-8&allowMultiQueries=true"/>    <property name="maxPoolSize" value="150"/>     <property name="minPoolSize" value="10"/>     <property name="initialPoolSize" value="20"/>     <property name="maxIdleTime" value="3600"/>     <property name="acquireIncrement" value="10"/>     <property name="idleConnectionTestPeriod" value="1800"/>    </bean>  <!-- slave -->  <bean id="slave" class="com.mchange.v2.c3p0.ComboPooledDataSource">    <property name="driverClass" value="${driverClassName_slave}"/>    <property name="user" value="${username_slave}"/>    <property name="password" value="${password_slave}"/>    <property name="jdbcUrl" value="${url_slave}?Unicode=true&characterEncoding=UTF-8"/>    <property name="maxPoolSize" value="150"/>     <property name="minPoolSize" value="10"/>     <property name="initialPoolSize" value="20"/>     <property name="maxIdleTime" value="3600"/>     <property name="acquireIncrement" value="10"/>     <property name="idleConnectionTestPeriod" value="1800"/>    </bean>  <!-- spring 动态数据源 -->  <bean id="dynamicDataSource" class="com.carl.dbUtil.DynamicDataSource">    <property name="targetDataSources">       <map key-type="java.lang.String">         <entry key="slave" value-ref="slave" />       </map>     </property>     <property name="defaultTargetDataSource" ref="master" />     </bean>   <!-- mybatis mapper config -->  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="dataSource" ref="dynamicDataSource"/>    <property name="configLocation" value="classpath:o2o_mybatis_config.xml"/>    <property name="mapperLocations" >      <list>        <value>classpath:sqlMap/*.xml</value>        <value>classpath*:/com/carl/o2o/**/*.xml</value>      </list>    </property>  </bean>  <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">    <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>  </bean>  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="basePackage" value="com.carl.o2o.**.mgr.dao" />  </bean>  <!-- 多数据源 aop -->  <bean id="DataSourceAspect" class="com.carl.dbUtil.DataSourceAspect" />  <aop:config>     <aop:advisor pointcut="execution(* com.carl.o2o.mgr.*.*(..))" advice-ref="DataSourceAspect" />  </aop:config>   <!-- 事务 -->  <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">      <property name="dataSource" ref="dynamicDataSource"></property>  </bean> </beans>

2、DynamicDataSource

DynamicDataSource使用Spring中的代码结合AOP实现多数据源切换.

public class DynamicDataSource extends AbstractRoutingDataSource {  public DynamicDataSource() {  }  protected Object determineCurrentLookupKey() {    return DBContextHolder.getDbType();  }  public Logger getParentLogger() {    return null;  }}

3、DBContextHolder

DynamicDataSource的辅助类,用于实际的切换多数据源。

public class DBContextHolder {  private static ThreadLocal<String> contextHolder = new ThreadLocal();  public static String MASTER = "master";  public static String SLAVE = "slave";  public DBContextHolder() {  }  public static String getDbType() {    String db = (String)contextHolder.get();    if(db == null) {      db = MASTER;    }    return db;  }  public static void setDbType(String str) {    contextHolder.set(str);  }  public static void setMaster() {    contextHolder.set(MASTER);  }  public static void setSlave() {    contextHolder.set(SLAVE);  }  public static void clearDBType() {    contextHolder.remove();  }}

4、DataSourceAspect

多数据源AOP切面编程实现。

public class DataSourceAspect implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {  private static final Logger log = LogManager.getLogger(DataSourceAspect.class);  public DataSourceAspect() {  }  public void before(Method m, Object[] args, Object target) throws Throwable {    try {      if(m != null) {        if((m.getName().startsWith("list") || m.getName().startsWith("select") || m.getName().startsWith("get")         || m.getName().startsWith("count")) && !m.getName().contains("FromMaster")) {          DBContextHolder.setDbType("slave");        } else {          DBContextHolder.setDbType("master");        }      }    } catch (Exception var5) {      log.error("data source aspect error.", var5);    }  }  public void after(JoinPoint point) {    log.info("clear db type after method.current id {}", new Object[]{Long.valueOf(Thread.currentThread().getId())});    DBContextHolder.clearDBType();  }  public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {  }  public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {    log.info("current db type {} when exception", new Object[]{DBContextHolder.getDbType()});    DBContextHolder.setDbType("master");  }}

以上就是 Spring AOP 动态多数据源的实例详解,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


  • 上一条:
    Request获取Session的方法总结
    下一条:
    Spring Quartz2 动态任务的实例详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客