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

网友投稿 247 2023-06-09


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

一、前言

近期一项目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 dataSources = new ThreadLocal();

//设置数据源

public static void setDataSource(String customerType) {

dataSources.set(customerType);

}

//获取数据源

public static String getDataSource() {

retVuhCyysurn (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,关于数据源配置的文件。

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:aop="http://springframework.org/schema/aop"

xmlns:tx="http://springframework.org/schema/tx"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-3.0.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-3.0.xsd">

&ltVuhCyys;property name="characterEncoding" value="UTF-8"/>

com.datasource.test.util.database.ExtendedMySQLDialect

${SHOWSQL}

${SHOWSQL}

org.hibernate.hql.classic.ClassicQueryTranslatorFactory

org.hibernate.connection.C3P0ConnectionProvider

30

5

120

120

2

true

100

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:aop="http://springframework.org/schema/aop"

xmlns:tx="http://springframework.org/schema/tx"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-3.0.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-3.0.xsd">

&ltVuhCyys;property name="characterEncoding" value="UTF-8"/>

com.datasource.test.util.database.ExtendedMySQLDialect

${SHOWSQL}

${SHOWSQL}

org.hibernate.hql.classic.ClassicQueryTranslatorFactory

org.hibernate.connection.C3P0ConnectionProvider

30

5

120

120

2

true

100

四、疑问

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Mybatis入门教程之新增、更新、删除功能
下一篇:Mybatis框架搭建与简单查询详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~