Jay
2024-10-14 441d3055fb0876835050d52123808b1c46a53179
iailab-framework/iailab-common-biz-tenant/src/main/java/com/iailab/framework/tenant/core/db/dynamic/TenantDsProcessor.java
@@ -4,8 +4,11 @@
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.processor.DsProcessor;
import com.iailab.framework.tenant.core.context.DataContextHolder;
import com.iailab.framework.tenant.core.context.TenantContextHolder;
import com.iailab.framework.tenant.core.service.TenantFrameworkService;
import com.iailab.module.infra.api.db.DataSourceConfigServiceApi;
import com.iailab.module.infra.api.db.dto.DataSourceConfigRespDTO;
import lombok.RequiredArgsConstructor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.context.annotation.Lazy;
@@ -46,19 +49,37 @@
    @Lazy
    private DefaultDataSourceCreator dataSourceCreator;
    @Resource
    @Lazy
    private DataSourceConfigServiceApi dataSourceConfigServiceApi;
    @Override
    public boolean matches(String key) {
        return Objects.equals(key, TenantDS.KEY);
        return Objects.equals(key, TenantDS.KEY) || Objects.equals(key, DataDS.KEY);
    }
    @Override
    public String doDetermineDatasource(MethodInvocation invocation, String key) {
        if (DataDS.KEY.equals(key)){
            // 获得数据源配置
            Long dataSourceId = DataContextHolder.getRequiredDataSourceId();
            DataSourceConfigRespDTO dataSourceConfigRespDTO = dataSourceConfigServiceApi.getDataSourceConfig(dataSourceId);
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setPoolName(dataSourceConfigRespDTO.getName());
            dataSourceProperty.setUrl(dataSourceConfigRespDTO.getUrl());
            dataSourceProperty.setUsername(dataSourceConfigRespDTO.getUsername());
            dataSourceProperty.setPassword(dataSourceConfigRespDTO.getPassword());
            // 创建 or 创建数据源,并返回数据源名字
            return createDatasourceIfAbsent(dataSourceProperty);
        }else if(TenantDS.KEY.equals(key)){
        // 获得数据源配置
        Long tenantId = TenantContextHolder.getRequiredTenantId();
        DataSourceProperty dataSourceProperty = tenantFrameworkService.getDataSourceProperty(tenantId);
        // 创建 or 创建数据源,并返回数据源名字
        return createDatasourceIfAbsent(dataSourceProperty);
    }
        return key;
    }
    private String createDatasourceIfAbsent(DataSourceProperty dataSourceProperty) {
        // 1. 重点:如果数据源不存在,则进行创建