|
| 1 | +package com.yomahub.liteflow.parser.sql.datasource.impl; |
| 2 | + |
| 3 | +import cn.hutool.core.util.ClassLoaderUtil; |
| 4 | +import cn.hutool.core.util.StrUtil; |
| 5 | +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; |
| 6 | +import com.yomahub.liteflow.exception.MissMavenDependencyException; |
| 7 | +import com.yomahub.liteflow.parser.sql.datasource.LiteFlowDataSourceConnect; |
| 8 | +import com.yomahub.liteflow.parser.sql.exception.ELSQLException; |
| 9 | +import com.yomahub.liteflow.parser.sql.vo.SQLParserVO; |
| 10 | +import com.yomahub.liteflow.spi.ContextAware; |
| 11 | +import com.yomahub.liteflow.spi.holder.ContextAwareHolder; |
| 12 | + |
| 13 | +import javax.sql.DataSource; |
| 14 | +import java.sql.Connection; |
| 15 | +import java.util.Map; |
| 16 | +import java.util.Optional; |
| 17 | + |
| 18 | +/** |
| 19 | + * 苞米豆动态数据源 |
| 20 | + * |
| 21 | + * @author tkc |
| 22 | + * @since 2.12.5 |
| 23 | + */ |
| 24 | +public class BaoMiDouDynamicDsConn implements LiteFlowDataSourceConnect { |
| 25 | + @Override |
| 26 | + public boolean filter(SQLParserVO config) { |
| 27 | + // 是否配置苞米豆动态数据源配置 |
| 28 | + boolean configFlag = Optional.ofNullable(config.getBaomidou()) |
| 29 | + .map(SQLParserVO.DataSourceConfig::getDataSourceName) |
| 30 | + .isPresent(); |
| 31 | + if (!configFlag) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + boolean classLoadFlag = ClassLoaderUtil.isPresent(Constant.LOAD_CLASS_NAME); |
| 35 | + if (!classLoadFlag) { |
| 36 | + throw new MissMavenDependencyException(Constant.MAVEN_GROUP_ID, Constant.MAVEN_ARTIFACT_ID); |
| 37 | + } |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public Connection getConn(SQLParserVO config) throws Exception { |
| 43 | + String dataSourceName = config.getBaomidou().getDataSourceName(); |
| 44 | + ContextAware contextAware = ContextAwareHolder.loadContextAware(); |
| 45 | + DynamicRoutingDataSource dynamicRoutingDataSource = contextAware.getBean(DynamicRoutingDataSource.class); |
| 46 | + Map<String, DataSource> dataSources = dynamicRoutingDataSource.getDataSources(); |
| 47 | + if (!dataSources.containsKey(dataSourceName)) { |
| 48 | + throw new ELSQLException(StrUtil.format("can not found {} datasource", dataSourceName)); |
| 49 | + } |
| 50 | + |
| 51 | + DataSource dataSource = dynamicRoutingDataSource.getDataSource(dataSourceName); |
| 52 | + return dataSource.getConnection(); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * 常量类 |
| 57 | + */ |
| 58 | + public static class Constant { |
| 59 | + public static final String LOAD_CLASS_NAME = "com.baomidou.dynamic.datasource.DynamicRoutingDataSource"; |
| 60 | + public static final String MAVEN_GROUP_ID = "com.baomidou"; |
| 61 | + public static final String MAVEN_ARTIFACT_ID = "dynamic-datasource-spring-boot-starter"; |
| 62 | + } |
| 63 | +} |
0 commit comments