SpringBoot2.x实现动态切换数据源(实现读写分离)

SpringBoot提供了org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource来动态的切换数据源。

可以借助ThreadLocal为每一个线程来选择合适的数据源。

源码分析:

//可以路由的数据源
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {

    @Nullable
    private Map<Object, Object> targetDataSources;

    @Nullable
    private Object defaultTargetDataSource;

    private boolean lenientFallback = true;

    private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
    //所有的数据源。
    @Nullable
    private Map<Object, DataSource> resolvedDataSources;
    //默认的数据源。
    @Nullable
    private DataSource resolvedDefaultDataSource;
    //决定目标数据源
    protected DataSource determineTargetDataSource() {
        Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
        //决定当前的key
        Object lookupKey = determineCurrentLookupKey();
        //在map中找到合适的value
        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;
    }
    //决定当前的key(可以使用ThreadLocal为每一个线程选择合适的key)。
    @Nullable
    protected abstract Object determineCurrentLookupKey();
}

代码实现

1. 定义枚举类:

public enum  DataSourceAddressEnum {
    /**
     * 主数据库
     */
    MASTER,
    /**
     * 从数据库
     */
    SLAVE;
}

2. 定义注解:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RoutingDataSource {

    /**
     * 路由的DataSource地址,默认为MASTER
     */
    DataSourceAddressEnum value() default DataSourceAddressEnum.MASTER;
}

3. 定义AOP代理,处理对应的注解:

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
@Order(10000)
@Slf4j
public class RoutingDataSourceAOP {

    @Pointcut("@annotation(com.tellme.config.datasource.RoutingDataSource)|| @within(com.tellme.config.datasource.RoutingDataSource)")
    public void routingDataSourcePointcut() {
    }

    @Around("routingDataSourcePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RoutingDataSource routerDataSource = method.getAnnotation(RoutingDataSource.class);
        // 如果没有设置则默认为 MASTER
        DataSourceAddressEnum dataSourceAddressEnum = Objects.isNull(routerDataSource) ?
                DataSourceAddressEnum.MASTER : routerDataSource.value();
        // 通过向ThreadLocal设置对应的key,来选择数据源,达到动态切换数据源的目的。
        DataSourceContextHolder.setCurrentDataSource(dataSourceAddressEnum);
        try {
            return joinPoint.proceed();
        } finally {
            DataSourceContextHolder.removeDataSource();
        }
    }
}

配置ThreadLocal:

public class DataSourceContextHolder {
    private static final ThreadLocal<DataSourceAddressEnum> CONTEXT_HOLDER = ThreadLocal.withInitial(() -> DataSourceAddressEnum.MASTER);

    public static void setCurrentDataSource(DataSourceAddressEnum dataSourceAddressEnum) {
        CONTEXT_HOLDER.set(dataSourceAddressEnum);
    }
    public static DataSourceAddressEnum getCurrentDataSource() {
        return CONTEXT_HOLDER.get();
    }
    public static void removeDataSource() {
        CONTEXT_HOLDER.remove();
    }
}

4. 初始化路由数据源类:

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

@Slf4j
public class RoutingDataSourceWithAddress extends AbstractRoutingDataSource {
    /**
     * 路由数据源类进行初始化
     * @param defaultTargetDataSource 默认的 DataSource
     * @param targetDataSources       配置的所有 DataSource
     */
    public RoutingDataSourceWithAddress(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
    }
    /**
     *配置的数据源
     */
    @Override
    protected Object determineCurrentLookupKey() {
        //通过ThreadLocal获取到key,来切换数据源
        DataSourceAddressEnum routingDataSourceAddressEnum = DataSourceContextHolder.getCurrentDataSource();
        if (log.isDebugEnabled()) {
            log.debug("routing data source address is {}", routingDataSourceAddressEnum.name());
        }
        return routingDataSourceAddressEnum;
    }

}

5. 数据源初始化:

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态配置数据源
 **/
@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class, DruidDataSource.class})
@EnableConfigurationProperties(MybatisProperties.class)
public class RoutingDataSourceAutoConfiguration {

    /**
     * 配置master数据源
     * 借助DruidDataSource类的配置,配置文件使用spring.datasource.druid.master的前缀。
     */
    @Bean(name = "masterDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create(this.getClass().getClassLoader())
                .type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }

    /**
     * 配置slave数据源,
     * 借助DruidDataSource类的配置,配置文件使用spring.datasource.druid.slave的前缀。
     */
    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.slave")
    public DataSource slaveDataSource(@Autowired @Qualifier("masterDataSource") DataSource masterDataSource) {
        return DataSourceBuilder.create(this.getClass().getClassLoader())
                .type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }

    /**
     * 初始化路由DataSource
     */
    @Bean
    public DataSource dataSource(
            @Autowired @Qualifier("masterDataSource") DataSource masterDataSource,
            @Autowired @Qualifier("slaveDataSource") DataSource slaveDataSource) {
        DataSource defaultTargetDataSource;
        Map<Object, Object> targetDataSources = ImmutableMap.of(
                DataSourceAddressEnum.MASTER, defaultTargetDataSource = masterDataSource,
                DataSourceAddressEnum.SLAVE, slaveDataSource);
        return new RoutingDataSourceWithAddress(defaultTargetDataSource, targetDataSources);
    }

    /**
     * 使用SqlSessionFactoryBean配置MyBatis的SqlSessionFactory
     **/
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(
            @Autowired @Qualifier("dataSource") DataSource routingDataSourceWithAddress,
            @Autowired MybatisProperties mybatisProperties,
            @Autowired ResourceLoader resourceLoader) throws Exception {

        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(routingDataSourceWithAddress);
        // 设置configuration
        org.apache.ibatis.session.Configuration configuration = mybatisProperties.getConfiguration();
        factory.setConfiguration(configuration);
        // 设置SqlSessionFactory属性
        String configLocation;
        if (StringUtils.isNotBlank(configLocation = mybatisProperties.getConfigLocation())) {
            factory.setConfigLocation(resourceLoader.getResource(configLocation));
        }
        Resource[] resolveMapperLocations;
        if (ArrayUtils.isNotEmpty(resolveMapperLocations = mybatisProperties.resolveMapperLocations())) {
            factory.setMapperLocations(resolveMapperLocations);
        }
        String typeHandlersPackage;
        if (StringUtils.isNotBlank(typeHandlersPackage = mybatisProperties.getTypeHandlersPackage())) {
            factory.setTypeHandlersPackage(typeHandlersPackage);
        }
        String typeAliasesPackage;
        if (StringUtils.isNotBlank(typeAliasesPackage = mybatisProperties.getTypeAliasesPackage())) {
            factory.setTypeAliasesPackage(typeAliasesPackage);
        }
        return factory.getObject();
    }

    /**
     * 使用routingDataSourceWithAddress配置数据库事务
     */
    @Bean
    @ConditionalOnMissingBean
    public DataSourceTransactionManager dataSourceTransactionManager(
            @Autowired @Qualifier("dataSource") DataSource routingDataSourceWithAddress) {
        return new DataSourceTransactionManager(routingDataSourceWithAddress);
    }

    /**
     * 编程式事务
     */
    @Bean
    public TransactionTemplate transactionTemplate(
            @Autowired @Qualifier("dataSourceTransactionManager") PlatformTransactionManager platformTransactionManager) {
        return new TransactionTemplate(platformTransactionManager);
    }

    @Bean
    @ConditionalOnMissingBean(RoutingDataSourceAOP.class)
    public RoutingDataSourceAOP routingDataSourceAOP() {
        return new RoutingDataSourceAOP();
    }
}

6. yml的配置

spring:
  datasource:
    name: mysql_test
    type: com.alibaba.druid.pool.DruidDataSource
    #druid相关配置
    druid:
      master:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_db?allowMultiQueries=true
        username: root
        password: 123qwe
        #初始化连接数
        initial-size: 10
        #最小活跃连接数
        min-size: 5
        #最大活跃连接数
        max-active: 30
        #获取连接的等待时间
        max-wait: 60000
      slave:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/exam?allowMultiQueries=true
        username: root
        password: 123qwe

代码实现

@RoutingDataSource(DataSourceAddressEnum.MASTER)
public void noTransactionMethod(UserT userT) {
    //查看事务是否失效
    TestTransactionService testTransactionService = (TestTransactionService) AopContext.currentProxy();
        testTransactionService.transactionMethod(userT);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 230,563评论 6 544
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,694评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,672评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,965评论 1 318
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,690评论 6 413
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 56,019评论 1 329
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 44,013评论 3 449
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 43,188评论 0 290
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,718评论 1 336
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,438评论 3 360
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,667评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,149评论 5 365
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,845评论 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,252评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,590评论 1 295
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,384评论 3 400
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,635评论 2 380