AbstractRoutingDataSource -- Spring提供的輕量級數據源切換方式

簡單多數據源配置

在一個普通Spring + Mybatis項目中,如果使用了多數據源,可以通過在dao層注入不同的SqlSessionTemplate來實現與不同數據庫交互的目的。單個SqlSessionTemplate注入容器的過程如下:

    <!-- 配置數據源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 註冊sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:config/mybatis-config.xml"/>
        <property name="typeAliasesPackage" value="com.wch.base.domain"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 配置dao接口掃描,配置sqlSessionTemplate -->
    <context:component-scan base-package="com.wch.base.mapper"/>
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory"/>
    </bean>

如果項目需要連接多個數據源,從DataSource、SqlSessionFactory、SqlSessionTemplate都需要配置多次,難於維護和管理。

AbstractRoutingDataSource

AbstractRoutingDataSource是spring-jdbc包提供的一個了AbstractDataSource的抽象類,它實現了DataSource接口的用於獲取數據庫連接的方法。

    @Override
    public Connection getConnection() throws SQLException {
        return determineTargetDataSource().getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return determineTargetDataSource().getConnection(username, password);
    }

    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;
    }

    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        this.targetDataSources = targetDataSources;
    }

AbstractRoutingDataSource的內部維護了一個名爲targetDataSources的Map,並提供的setter方法用於設置數據源關鍵字與數據源的關係,實現類被要求實現其determineCurrentLookupKey()方法,由此方法的返回值決定具體從哪個數據源中獲取連接。

數據源動態切換

AbstractRoutingDataSource提供了程序運行時動態切換數據源的方法,在dao類或方法上標註需要訪問數據源的關鍵字,路由到指定數據源,獲取連接。

數據源切換方法

維護一個static變量datasourceContext用於記錄每個線程需要使用的數據源關鍵字。並提供切換、讀取、清除數據源配置信息的方法。

@Slf4j
public class DataSourceContextHolder {

    private static ThreadLocal<String> datasourceContext = new ThreadLocal<>();

    public static void switchDataSource(String datasource) {
        log.debug("switchDataSource: {}", datasource);
        datasourceContext.set(datasource);
    }

    public static String getDataSource() {
        return datasourceContext.get();
    }

    public static void clear() {
        datasourceContext.remove();
    }
}

實現AbstractRoutingDataSource

public class RoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSource();
    }
}

配置數據源信息

# master datasource
ds.financial.master.driverClassName=com.mysql.jdbc.Driver
ds.financial.master.url=jdbc:mysql://127.0.0.1:3306/financial?useUnicode=true&characterEncoding=utf8&useSSL=true
ds.financial.master.username=root
ds.financial.master.password=
ds.financial.master.type=com.alibaba.druid.pool.DruidDataSource

# slave datasource
ds.financial.slave.driverClassName=com.mysql.jdbc.Driver
ds.financial.slave.url=jdbc:mysql://127.0.0.1:3306/financial_slave?useUnicode=true&characterEncoding=utf8&useSSL=true
ds.financial.slave.username=root
ds.financial.slave.password=
ds.financial.slave.type=com.alibaba.druid.pool.DruidDataSource

注入數據源

@Configuration
public class DataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "ds.financial.master")
    public DataSource financialMasterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "ds.financial.slave")
    public DataSource financialSlaveDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "routingDataSource")
    public RoutingDataSource routingDataSource() {
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("financial-master", financialMasterDataSource());
        dataSourceMap.put("financial-slave", financialSlaveDataSource());

        RoutingDataSource routingDataSource = new RoutingDataSource();
        routingDataSource.setTargetDataSources(dataSourceMap);
        routingDataSource.setDefaultTargetDataSource(financialMasterDataSource());
        return routingDataSource;
    }
}

Mybatis配置

@Configuration
public class MyBatisConfig {

    @Resource(name = "routingDataSource")
    private RoutingDataSource routingDataSource;

    /**
     * routingDataSource sqlSessionFactory
     *
     * @return
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(routingDataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/**/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.wch.financial.domain");
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 註冊 sqlSessionTemplate
     *
     * @param sqlSessionFactory
     * @return
     */
    @Bean
    public SqlSessionTemplate financialMasterSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

關鍵字標記生命週期管理

當一個線程執行某個dao方法時讀取此方法配置的數據源關鍵字並寫入datasourceContext,在此方法執行完成後清除datasourceContext中的標記。此生命週期使用aop實現。

標記註解

用於dao類或方法上。

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {

    String name() default "";
}

標記註解的方法的切面處理

@Aspect
@Component
public class HandleDatasourceAspect {

    @Pointcut("@annotation(com.wch.financial.config.DataSource)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void beforeExecute(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        DataSource annotation = method.getAnnotation(DataSource.class);
        if (null == annotation) {
            annotation = joinPoint.getTarget().getClass().getAnnotation(DataSource.class);
        }
        if (null != annotation) {
            // 切換數據源
            DataSourceContextHolder.switchDataSource(annotation.name());
        }
    }

    @After("pointcut()")
    public void afterExecute() {
        DataSourceContextHolder.clear();
    }
}

使用

在dao實現類的類或方法上標註@DataSource註解。

@Repository
public class ProductDaoImpl implements ProductDao {

    @Resource
    private SqlSessionTemplate sst;

    @Override
    @DataSource(name = "financial-slave")
    public List<Product> selectProduct() {
        return sst.selectList("financial.product.selectProduct");
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章