0

0

SpringBoot基于AbstractRoutingDataSource如何实现多数据源动态切换

WBOY

WBOY

发布时间:2023-05-31 10:43:52

|

1257人浏览过

|

来源于亿速云

转载

一、场景

在生产业务中,有一些任务执行了耗时较长的查询操作,在实时性要求不高的时候,我们希望将这些查询sql分离出来,去从库查询,以减少应用对主数据库的压力。

一种方案是在配置文件中配置多个数据源,然后通过配置类来获取数据源以及mapper相关的扫描配置,不同的数据源配置不佟的mapper扫描位置,然后需要哪一个数据源就注入哪一个mapper接口即可,这种方法比较简单。特征是通过mapper扫描位置区分数据源。

一种可行的方案是事先设置一个默认的数据源,同时定义多个其他的数据源,利用aop实现注解方式来切换数据源。对AbstractRoutingDataSource类进行继承是实现这种方案的关键。这是本文的重点。

二、原理

AbstractRoutingDataSource的多数据源动态切换的核心逻辑是:在程序运行时,把数据源数据源通过 AbstractRoutingDataSource 动态织入到程序中,灵活的进行数据源切换。
基于AbstractRoutingDataSource的多数据源动态切换,可以实现读写分离。逻辑如下:

/**
     * 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;
    }
/**
     * Determine the current lookup key. This will typically be
     * implemented to check a thread-bound transaction context.
     * 

Allows for arbitrary keys. The returned key needs * to match the stored lookup key type, as resolved by the * {@link #resolveSpecifiedLookupKey} method. */ @Nullable protected abstract Object determineCurrentLookupKey();

通过实现抽象方法determineCurrentLookupKey指定需要切换的数据源

三、代码示例

示例中主要依赖 

com.alibaba.druid;tk.mybatis

定义一个类用于关联数据源。通过 TheadLocal 来保存每个线程选择哪个数据源的标志(key)

@Slf4j
public class DynamicDataSourceContextHolder {
 
 
    private static final ThreadLocal contextHolder = new ThreadLocal();
    public static List dataSourceIds = new ArrayList();
 
    public static void setDataSourceType(String dataSourceType) {
        log.info("设置当前数据源为{}",dataSourceType);
        contextHolder.set(dataSourceType);
    }
 
    public static String getDataSourceType() {
        return contextHolder.get() ;
    }
 
    public static void clearDataSourceType() {
        contextHolder.remove();
    }
 
    public static boolean containsDataSource(String dataSourceId){
        log.info("list = {},dataId={}", JSON.toJSON(dataSourceIds),dataSourceId);
        return dataSourceIds.contains(dataSourceId);
    }
}

继承

AbstractRoutingDataSource

public class DynamicDataSource  extends AbstractRoutingDataSource {
 
    @Override
    protected Object determineCurrentLookupKey() {
 
        return  DynamicDataSourceContextHolder.getDataSourceType();
    }
}

配置主数据库master 与从数据库slave(略)。数据源配置可以从简

@Configuration
@tk.mybatis.spring.annotation.MapperScan(value = {"com.server.dal.dao"})
@ConditionalOnProperty(name = "java.druid.datasource.master.url")
public class JavaDruidDataSourceConfiguration {
 
    private static final Logger logger = LoggerFactory.getLogger(JavaDruidDataSourceConfiguration.class);
 
    @Resource
    private JavaDruidDataSourceProperties druidDataSourceProperties;
    @Primary
    @Bean(name = "masterDataSource", initMethod = "init", destroyMethod = "close")
    @ConditionalOnMissingBean(name = "masterDataSource")
    public DruidDataSource javaReadDruidDataSource() {
 
        DruidDataSource result = new DruidDataSource();
 
        try {
//            result.setName(druidDataSourceProperties.getName());
            result.setUrl(druidDataSourceProperties.getUrl());
            result.setUsername(druidDataSourceProperties.getUsername());
            result.setPassword(druidDataSourceProperties.getPassword());
            result.setConnectionProperties(
                    "config.decrypt=false;config.decrypt.key=" + druidDataSourceProperties.getPwdPublicKey());
            result.setFilters("config");
            result.setMaxActive(druidDataSourceProperties.getMaxActive());
            result.setInitialSize(druidDataSourceProperties.getInitialSize());
            result.setMaxWait(druidDataSourceProperties.getMaxWait());
            result.setMinIdle(druidDataSourceProperties.getMinIdle());
            result.setTimeBetweenEvictionRunsMillis(druidDataSourceProperties.getTimeBetweenEvictionRunsMillis());
            result.setMinEvictableIdleTimeMillis(druidDataSourceProperties.getMinEvictableIdleTimeMillis());
            result.setValidationQuery(druidDataSourceProperties.getValidationQuery());
            result.setTestWhileIdle(druidDataSourceProperties.isTestWhileIdle());
            result.setTestOnBorrow(druidDataSourceProperties.isTestOnBorrow());
            result.setTestOnReturn(druidDataSourceProperties.isTestOnReturn());
            result.setPoolPreparedStatements(druidDataSourceProperties.isPoolPreparedStatements());
            result.setMaxOpenPreparedStatements(druidDataSourceProperties.getMaxOpenPreparedStatements());
 
            if (druidDataSourceProperties.isEnableMonitor()) {
                StatFilter filter = new StatFilter();
                filter.setLogSlowSql(druidDataSourceProperties.isLogSlowSql());
                filter.setMergeSql(druidDataSourceProperties.isMergeSql());
                filter.setSlowSqlMillis(druidDataSourceProperties.getSlowSqlMillis());
                List list = new ArrayList<>();
                list.add(filter);
                result.setProxyFilters(list);
            }
 
        } catch (Exception e) {
 
            logger.error("数据源加载失败:", e);
 
        } finally {
            result.close();
        }
 
 
        return result;
    }
}

注意主从数据库的bean name

Batch GPT
Batch GPT

使用AI批量处理数据、自动执行任务

下载

配置DynamicDataSource 

  • targetDataSources 存放数据源的k-v对

  • defaultTargetDataSource 存放默认数据源

配置事务管理器和SqlSessionFactoryBean

@Configuration
public class DynamicDataSourceConfig {
    private static final String MAPPER_LOCATION = "classpath*:sqlmap/dao/*Mapper.xml";
 
    @Bean(name = "dynamicDataSource")
    public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DruidDataSource masterDataSource,
                                               @Qualifier("slaveDataSource") DruidDataSource slaveDataSource) {
        Map targetDataSource = new HashMap<>();
        DynamicDataSourceContextHolder.dataSourceIds.add("masterDataSource");
        targetDataSource.put("masterDataSource", masterDataSource);
        DynamicDataSourceContextHolder.dataSourceIds.add("slaveDataSource");
        targetDataSource.put("slaveDataSource", slaveDataSource);
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSource);
        dataSource.setDefaultTargetDataSource(masterDataSource);
        return dataSource;
    }
 
    @Primary
    @Bean(name = "javaTransactionManager")
    @ConditionalOnMissingBean(name = "javaTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("dynamicDataSource") DynamicDataSource druidDataSource) {
        return new DataSourceTransactionManager(druidDataSource);
    }
 
    @Bean(name = "sqlSessionFactoryBean")
    public SqlSessionFactoryBean myGetSqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource  dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources(MAPPER_LOCATION));
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
}

定义一个注解用于指定数据源

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
    String value();
}

切面的业务逻辑。注意指定order,以确保在开启事务之前执行 。

@Aspect
@Slf4j
@Order(-1)
@Component
public class DataSourceAop {
 
    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource) {
        String dsId = targetDataSource.value();
        if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
            log.error("数据源[{}]不存在,使用默认数据源 > {}" + targetDataSource.value() + point.getSignature());
        } else {
            log.info("UseDataSource : {} > {}" + targetDataSource.value() + point.getSignature());
            DynamicDataSourceContextHolder.setDataSourceType(targetDataSource.value());
 
        }
    }
 
    @After("@annotation(targetDataSource)")
    public void restoreDataSource(JoinPoint point, TargetDataSource targetDataSource) {
        log.info("RevertDataSource : {} > {}"+targetDataSource.value()+point.getSignature());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}

以上略去了pom.xml和application.yml

使用示例

    @Resource
    private ShopBillDOMapper shopBillDOMapper;
 
//使用默认数据源
    public ShopBillBO queryTestData(Integer id){
 
        return shopBillDOMapper.getByShopBillId(id);
    }
 
//切换到指定的数据源
    @TargetDataSource("slaveDataSource")
    public ShopBill queryTestData2(Integer id){
        return shopBillDOMapper.getByShopBillId(id);
    }

如果返回不同的结果就成功了!

相关专题

更多
数据分析工具有哪些
数据分析工具有哪些

数据分析工具有Excel、SQL、Python、R、Tableau、Power BI、SAS、SPSS和MATLAB等。详细介绍:1、Excel,具有强大的计算和数据处理功能;2、SQL,可以进行数据查询、过滤、排序、聚合等操作;3、Python,拥有丰富的数据分析库;4、R,拥有丰富的统计分析库和图形库;5、Tableau,提供了直观易用的用户界面等等。

675

2023.10.12

SQL中distinct的用法
SQL中distinct的用法

SQL中distinct的语法是“SELECT DISTINCT column1, column2,...,FROM table_name;”。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

319

2023.10.27

SQL中months_between使用方法
SQL中months_between使用方法

在SQL中,MONTHS_BETWEEN 是一个常见的函数,用于计算两个日期之间的月份差。想了解更多SQL的相关内容,可以阅读本专题下面的文章。

345

2024.02.23

SQL出现5120错误解决方法
SQL出现5120错误解决方法

SQL Server错误5120是由于没有足够的权限来访问或操作指定的数据库或文件引起的。想了解更多sql错误的相关内容,可以阅读本专题下面的文章。

1084

2024.03.06

sql procedure语法错误解决方法
sql procedure语法错误解决方法

sql procedure语法错误解决办法:1、仔细检查错误消息;2、检查语法规则;3、检查括号和引号;4、检查变量和参数;5、检查关键字和函数;6、逐步调试;7、参考文档和示例。想了解更多语法错误的相关内容,可以阅读本专题下面的文章。

355

2024.03.06

oracle数据库运行sql方法
oracle数据库运行sql方法

运行sql步骤包括:打开sql plus工具并连接到数据库。在提示符下输入sql语句。按enter键运行该语句。查看结果,错误消息或退出sql plus。想了解更多oracle数据库的相关内容,可以阅读本专题下面的文章。

673

2024.04.07

sql中where的含义
sql中where的含义

sql中where子句用于从表中过滤数据,它基于指定条件选择特定的行。想了解更多where的相关内容,可以阅读本专题下面的文章。

566

2024.04.29

sql中删除表的语句是什么
sql中删除表的语句是什么

sql中用于删除表的语句是drop table。语法为drop table table_name;该语句将永久删除指定表的表和数据。想了解更多sql的相关内容,可以阅读本专题下面的文章。

409

2024.04.29

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Redis6入门到精通超详细教程
Redis6入门到精通超详细教程

共47课时 | 5.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号