| | |
| | | package com.ltkj.db; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; |
| | | import javax.sql.DataSource; |
| | | import java.util.Map; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | |
| | | @Slf4j |
| | | public class HospDynamicDataSource extends AbstractRoutingDataSource { |
| | | |
| | | private final Map<Object, Object> targetDataSources = new ConcurrentHashMap<>(); // 存储所有数据源 |
| | | |
| | | @Override |
| | | protected Object determineCurrentLookupKey() { |
| | | return DataSourceContextHolder.getDataSourceKey(); // 根据上下文获取当前数据源的键 |
| | | String key = DataSourceContextHolder.getDataSourceKey(); |
| | | log.info("当前数据源 ->{}",key); |
| | | return key; // 根据上下文获取当前数据源的键 |
| | | } |
| | | |
| | | // 添加目标数据源 |
| | | public void addTargetDataSource(String key, DataSource dataSource) { |
| | | targetDataSources.put(key, dataSource); |
| | | super.setTargetDataSources(new ConcurrentHashMap<>(targetDataSources)); // 更新目标数据源 |
| | | super.afterPropertiesSet(); // 重新初始化数据源 |
| | | if (dataSource != null) { |
| | | targetDataSources.put(key, dataSource); |
| | | super.setTargetDataSources(new ConcurrentHashMap<>(targetDataSources)); // 更新目标数据源 |
| | | super.afterPropertiesSet(); // 重新初始化数据源 |
| | | } |
| | | } |
| | | |
| | | // 允许外部访问所有目标数据源 |