当前位置: 移动技术网 > IT编程>开发语言>Java > Spring(AbstractRoutingDataSource)实现动态数据源切换示例

Spring(AbstractRoutingDataSource)实现动态数据源切换示例

2019年07月22日  | 移动技术网IT编程  | 我要评论

一、前言

近期一项目a需实现数据同步到另一项目b数据库中,在不改变b项目的情况下,只好选择项目a中切换数据源,直接把数据写入项目b的数据库中。这种需求,在数据同步与定时任务中经常需要。

那么问题来了,该如何解决多数据源问题呢?不光是要配置多个数据源,还得能灵活动态的切换数据源。以spring+hibernate框架项目为例:

单个数据源绑定给sessionfactory,再在dao层操作,若多个数据源的话,那不是就成了下图:

   

可见,sessionfactory都写死在了dao层,若我再添加个数据源的话,则又得添加一个sessionfactory。所以比较好的做法应该是下图:

接下来就为大家讲解下如何用spring来整合这些数据源,同样以spring+hibernate配置为例。

二、实现原理

1、扩展spring的abstractroutingdatasource抽象类(该类充当了datasource的路由中介, 能有在运行时, 根据某种key值来动态切换到真正的datasource上。)

从abstractroutingdatasource的源码中:

复制代码 代码如下:

public abstract class abstractroutingdatasource extends abstractdatasource implements initializingbean

我们可以看到,它继承了abstractdatasource,而abstractdatasource不就是javax.sql.datasource的子类,so我们可以分析下它的getconnection方法:

public connection getconnection() throws sqlexception { 
 return determinetargetdatasource().getconnection(); 
} 
 
public connection getconnection(string username, string password) throws sqlexception { 
  return determinetargetdatasource().getconnection(username, password); 
}

获取连接的方法中,重点是determinetargetdatasource()方法,看源码:

/** 
  * retrieve the current target datasource. determines the 
  * {@link #determinecurrentlookupkey() current lookup key}, performs 
  * a lookup in the {@link #settargetdatasources targetdatasources} map, 
  * falls back to the specified 
  * {@link #setdefaulttargetdatasource default target datasource} if necessary. 
  * @see #determinecurrentlookupkey() 
  */ 
 protected datasource determinetargetdatasource() { 
  assert.notnull(this.resolveddatasources, "datasource router not initialized"); 
  object lookupkey = determinecurrentlookupkey(); 
  datasource datasource = this.resolveddatasources.get(lookupkey); 
  if (datasource == null && (this.lenientfallback || lookupkey == null)) { 
   datasource = this.resolveddefaultdatasource; 
  } 
  if (datasource == null) { 
   throw new illegalstateexception("cannot determine target datasource for lookup key [" + lookupkey + "]"); 
  } 
  return datasource; 
 }

上面这段源码的重点在于determinecurrentlookupkey()方法,这是abstractroutingdatasource类中的一个抽象方法,而它的返回值是你所要用的数据源datasource的key值,有了这个key值,resolveddatasource(这是个map,由配置文件中设置好后存入的)就从中取出对应的datasource,如果找不到,就用配置默认的数据源。

看完源码,应该有点启发了吧,没错!你要扩展abstractroutingdatasource类,并重写其中的determinecurrentlookupkey()方法,来实现数据源的切换:

package com.datasource.test.util.database;
 
import org.springframework.jdbc.datasource.lookup.abstractroutingdatasource;
 
/**
 * 获取数据源(依赖于spring)
 * @author linhy
 */
public class dynamicdatasource extends abstractroutingdatasource{
 @override
 protected object determinecurrentlookupkey() {
  return datasourceholder.getdatasource();
 }
}

datasourceholder这个类则是我们自己封装的对数据源进行操作的类:

package com.datasource.test.util.database;
 
/**
 * 数据源操作
 * @author linhy
 */
public class datasourceholder {
 //线程本地环境
 private static final threadlocal<string> datasources = new threadlocal<string>();
 //设置数据源
 public static void setdatasource(string customertype) {
  datasources.set(customertype);
 }
 //获取数据源
 public static string getdatasource() {
  return (string) datasources.get();
 }
 //清除数据源
 public static void cleardatasource() {
  datasources.remove();
 }
 
}

2、有人就要问,那你setdatasource这方法是要在什么时候执行呢?当然是在你需要切换数据源的时候执行啦。手动在代码中调用写死吗?这是多蠢的方法,当然要让它动态咯。所以我们可以应用spring aop来设置,把配置的数据源类型都设置成为注解标签,在service层中需要切换数据源的方法上,写上注解标签,调用相应方法切换数据源咯(就跟你设置事务一样):

@datasource(name=datasource.slave1)
public list getproducts(){

当然,注解标签的用法可能很少人用到,但它可是个好东西哦,大大的帮助了我们开发:

package com.datasource.test.util.database;
 
import java.lang.annotation.*;
 
@target({elementtype.method, elementtype.type})
@retention(retentionpolicy.runtime)
@documented
public @interface datasource {
 string name() default datasource.master;
 
 public static string master = "datasource1";
 
 public static string slave1 = "datasource2";
 
 public static string slave2 = "datasource3";
 
}

三、配置文件

为了精简篇幅,省略了无关本内容主题的配置。

项目中单独分离出application-database.xml,关于数据源配置的文件。

<?xml version="1.0" encoding="utf-8"?>
<!-- spring 数据库相关配置 放在这里 -->
<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: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-3.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 
 <bean id = "datasource1" class = "com.mysql.jdbc.jdbc2.optional.mysqldatasource"> 
  <property name="url" value="${db1.url}"/>
  <property name = "user" value = "${db1.user}"/>
  <property name = "password" value = "${db1.pwd}"/>
  <property name="autoreconnect" value="true"/>
  <property name="useunicode" value="true"/>
  <property name="characterencoding" value="utf-8"/>
 </bean>
 
 <bean id = "datasource2" class = "com.mysql.jdbc.jdbc2.optional.mysqldatasource">
  <property name="url" value="${db2.url}"/>
  <property name = "user" value = "${db2.user}"/>
  <property name = "password" value = "${db2.pwd}"/>
  <property name="autoreconnect" value="true"/>
  <property name="useunicode" value="true"/>
  <property name="characterencoding" value="utf-8"/>
 </bean>
 
 <bean id = "datasource3" class = "com.mysql.jdbc.jdbc2.optional.mysqldatasource">
  <property name="url" value="${db3.url}"/>
  <property name = "user" value = "${db3.user}"/>
  <property name = "password" value = "${db3.pwd}"/>
  <property name="autoreconnect" value="true"/>
  <property name="useunicode" value="true"/>
  <property name="characterencoding" value="utf-8"/>
 </bean>
 <!-- 配置多数据源映射关系 -->
 <bean id="datasource" class="com.datasource.test.util.database.dynamicdatasource">
  <property name="targetdatasources">
   <map key-type="java.lang.string">
  <entry key="datasource1" value-ref="datasource1"></entry>
    <entry key="datasource2" value-ref="datasource2"></entry>
    <entry key="datasource3" value-ref="datasource3"></entry>
   </map>
  </property>
 <!-- 默认目标数据源为你主库数据源 -->
  <property name="defaulttargetdatasource" ref="datasource1"/>
 </bean>
 
 <bean id="sessionfactoryhibernate" class="org.springframework.orm.hibernate3.localsessionfactorybean">
  <property name="datasource" ref="datasource"/>
  <property name="hibernateproperties">
   <props>
    <prop key="hibernate.dialect">com.datasource.test.util.database.extendedmysqldialect</prop>
    <prop key="hibernate.show_sql">${showsql}</prop>
    <prop key="hibernate.format_sql">${showsql}</prop>
    <prop key="query.factory_class">org.hibernate.hql.classic.classicquerytranslatorfactory</prop>
    <prop key="hibernate.connection.provider_class">org.hibernate.connection.c3p0connectionprovider</prop>
    <prop key="hibernate.c3p0.max_size">30</prop>
    <prop key="hibernate.c3p0.min_size">5</prop>
    <prop key="hibernate.c3p0.timeout">120</prop>
    <prop key="hibernate.c3p0.idle_test_period">120</prop>
    <prop key="hibernate.c3p0.acquire_increment">2</prop>
    <prop key="hibernate.c3p0.validate">true</prop>
    <prop key="hibernate.c3p0.max_statements">100</prop>
   </props>
  </property>
 </bean>
 
 <bean id="hibernatetemplate" class="org.springframework.orm.hibernate3.hibernatetemplate">
  <property name="sessionfactory" ref="sessionfactoryhibernate"/>
 </bean>
 
 <bean id="datasourceexchange" class="com.datasource.test.util.database.datasourceexchange"/>
 
 <bean id="transactionmanager" class="org.springframework.orm.hibernate3.hibernatetransactionmanager">
  <property name="sessionfactory" ref="sessionfactoryhibernate"/>
 </bean>
 
 <tx:advice id="txadvice" transaction-manager="transactionmanager">
  <tx:attributes>
   <tx:method name="insert*" propagation="nested" rollback-for="exception"/>
   <tx:method name="add*" propagation="nested" rollback-for="exception"/>
   <tx:method name="update*" propagation="nested" rollback-for="exception"/>
   <tx:method name="modify*" propagation="nested" rollback-for="exception"/>
   <tx:method name="edit*" propagation="nested" rollback-for="exception"/>
   <tx:method name="del*" propagation="nested" rollback-for="exception"/>
   <tx:method name="save*" propagation="nested" rollback-for="exception"/>
   <tx:method name="send*" propagation="nested" rollback-for="exception"/>
   <tx:method name="get*" read-only="true"/>
   <tx:method name="find*" read-only="true"/>
   <tx:method name="query*" read-only="true"/>
   <tx:method name="search*" read-only="true"/>
   <tx:method name="select*" read-only="true"/>
   <tx:method name="count*" read-only="true"/>
  </tx:attributes>
 </tx:advice>
 
 <aop:config>
  <aop:pointcut id="service" expression="execution(* com.datasource..*.service.*.*(..))"/>
  <!-- 关键配置,切换数据源一定要比持久层代码更先执行(事务也算持久层代码) -->
  <aop:advisor advice-ref="txadvice" pointcut-ref="service" order="2"/>
  <aop:advisor advice-ref="datasourceexchange" pointcut-ref="service" order="1"/>
 </aop:config>
 
</beans>

四、疑问

多数据源切换是成功了,但牵涉到事务呢?单数据源事务是ok的,但如果多数据源需要同时使用一个事务呢?这个问题有点头大,网络上有人提出用atomikos开源项目实现jta分布式事务处理。你怎么看?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网