baomidou / dynamic-datasource

dynamic datasource for springboot 多数据源 动态数据源 主从分离 读写分离 分布式事务
https://www.kancloud.cn/tracy5546/dynamic-datasource/2264611
Apache License 2.0
4.75k stars 1.19k forks source link

关于数据源的优雅下线 #614

Closed yuxiao97 closed 5 months ago

yuxiao97 commented 10 months ago

Please fill it out carefully, or it will be closed. 请认真填写,不然会直接关闭。

Enviroment

JDK Version(required): jdk8+ SpringBoot Version(required): 2.6.14 dynamic-datasource-spring-boot-starter Version(required): 3.5.1,4.2.0 druid Version(optional): HikariCP

Describe what happened

在关闭数据源时,会出现数据连接异常问题

Expected Result: 期望在关闭数据源时能够优雅,做到业务无损

Actual Result: 在关闭数据源时,会出现数据源连接异常,导致业务损。 以下是4.2.0版本中的源码

public synchronized void removeDataSource(String ds) {
        if (!DsStrUtils.hasText(ds)) {
            throw new RuntimeException("remove parameter could not be empty");
        } else if (this.primary.equals(ds)) {
            throw new RuntimeException("could not remove primary datasource");
        } else {
            if (this.dataSourceMap.containsKey(ds)) {
                DataSource dataSource = (DataSource)this.dataSourceMap.remove(ds);
                this.closeDataSource(ds, dataSource, this.graceDestroy);
                if (ds.contains("_")) {
                    String group = ds.split("_")[0];
                    if (this.groupDataSources.containsKey(group)) {
                        DataSource oldDataSource = ((GroupDataSource)this.groupDataSources.get(group)).removeDatasource(ds);
                        if (oldDataSource == null) {
                            log.warn("fail for remove datasource from group. dataSource: {} ,group: {}", ds, group);
                        }
                    }
                }

                log.info("dynamic-datasource - remove the database named [{}] success", ds);
            } else {
                log.warn("dynamic-datasource - could not find a database named [{}]", ds);
            }

        }
    }

有group的时候,建议先从group中移除,不要让业务选择到,再执行数据源的close动作,这样就不会出现先关闭数据源再移除分组数据导致的业务获取到正在关闭的连接。

If there is an exception,or aop invalid,please attach the exception trace:

Just paste your stack trace here!

Steps to reproduce

huayanYu commented 10 months ago

欢迎PR