| | |
| | | package com.ltkj.framework.datasource; |
| | | |
| | | import java.util.Map; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import javax.sql.DataSource; |
| | | |
| | | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; |
| | |
| | | * @author ltkj |
| | | */ |
| | | public class DynamicDataSource extends AbstractRoutingDataSource { |
| | | private final Map<Object, Object> targetDataSources = new ConcurrentHashMap<>(); // 存储所有数据源 |
| | | public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) { |
| | | super.setDefaultTargetDataSource(defaultTargetDataSource); |
| | | super.setTargetDataSources(targetDataSources); |
| | |
| | | |
| | | @Override |
| | | protected Object determineCurrentLookupKey() { |
| | | System.out.println("当前数据源 -> "+ DynamicDataSourceContextHolder.getDataSourceType()); |
| | | return DynamicDataSourceContextHolder.getDataSourceType(); |
| | | } |
| | | |
| | | public void addTargetDataSource(String key, DataSource dataSource) { |
| | | targetDataSources.put(key, dataSource); |
| | | super.setTargetDataSources(new ConcurrentHashMap<>(targetDataSources)); // 更新目标数据源 |
| | | super.afterPropertiesSet(); // 重新初始化数据源 |
| | | } |
| | | |
| | | // 允许外部访问所有目标数据源 |
| | | @Override |
| | | public void setTargetDataSources(Map<Object, Object> targetDataSources) { |
| | | super.setTargetDataSources(targetDataSources); |
| | | } |
| | | |
| | | public Map<Object, Object> getTargetDataSources() { |
| | | return targetDataSources; // 获取所有目标数据源 |
| | | } |
| | | } |
| | | } |