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 targetDataSources = new ConcurrentHashMap<>(); // 存储所有数据源 @Override protected Object determineCurrentLookupKey() { String key = DataSourceContextHolder.getDataSourceKey(); log.info("当前数据源 ->{}",key); return key; // 根据上下文获取当前数据源的键 } // 添加目标数据源 public void addTargetDataSource(String key, DataSource dataSource) { if (dataSource != null) { targetDataSources.put(key, dataSource); super.setTargetDataSources(new ConcurrentHashMap<>(targetDataSources)); // 更新目标数据源 super.afterPropertiesSet(); // 重新初始化数据源 } } // 允许外部访问所有目标数据源 @Override public void setTargetDataSources(Map targetDataSources) { super.setTargetDataSources(targetDataSources); } public Map getTargetDataSources() { return targetDataSources; // 获取所有目标数据源 } }