datasource数据源_Spring实现动态数据源

本文介绍了如何在Spring+Hibernate框架下实现动态数据源,主要通过扩展AbstractRoutingDataSource类并结合DataSourceHolder进行数据源切换。在Service层使用自定义注解@DataSource标记需要切换数据源的方法,利用Spring AOP进行拦截并动态设置数据源。
摘要由CSDN通过智能技术生成

引子

数据源这个词大家并不陌生,但什么是动态数据源呢?动态数据源是为了解决一个项目需连接多个数据源并可在开发过程中根据场景动态切换数据源的问题。所谓动态即不是写死的连接那个数据库,而是根据需要判定连接哪个数据库。最常见的场景就是读写分离,查询连读库,其他的连写库。下面我们以Spring+Hibernate框架为例,看如果实现。

1e47493a04e2847971be9e47bd0b4dee.png

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

e53fec8614c5b3a5b41286b3cb5bc841.png

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

d2663145eee8804538f415d1a6fbae63.png

实现原理

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

从AbstractRoutingDataSource的源码中:

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean

我们可以看到,它继承了AbstractDataSource,而AbstractDataSource就是javax.sql.DataSource的子类,所以我们分析下它的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() {

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,关于数据源配置的文件如下。当然这里面还涉及到通过AOP实现注解的拦截并设置相应数据源,最后在Spring中配置AOP。(需要切面代码的同学可以私信我)

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">

com.datasource.test.util.database.ExtendedMySQLDialect

${SHOWSQL}

${SHOWSQL}

org.hibernate.hql.classic.ClassicQueryTranslatorFactory

org.hibernate.connection.C3P0ConnectionProvider

30

5

120

120

2

true

100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值