| | |
| | | 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; |
| | |
| | | @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. 重点:如果数据源不存在,则进行创建 |