本文提供方法僅供相似簡單業務場景,在生產環境和複雜的業務場景 請使用分庫分表的中間件(例如mycat)或者框架 sharding-sphere (一直在用)等git
// 默認的事務管理器 ppublic class DataSourceTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager, InitializingBean { // 啓動時候注入一個數據源 public void setDataSource(@Nullable DataSource dataSource) { if (dataSource instanceof TransactionAwareDataSourceProxy) { this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource(); } else { this.dataSource = dataSource; } } 」
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean { // 用戶設置的所有的數據源配置 @Nullable private Map<Object, Object> targetDataSources; // 爲空默認的數據源配置 @Nullable private Object defaultTargetDataSource; // 路由鍵查找實現 private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); // 最終有效的數據源配置(通常清空對應上邊用戶的設置) @Nullable private Map<Object, DataSource> resolvedDataSources; }
@Slf4j public class DynamicDataSource extends AbstractRoutingDataSource { /** * 指定路由Key,這裏很簡單 獲取 threadLocal 中目標key 便可 * * @return */ @Override protected Object determineCurrentLookupKey() { return DynamicDataSourceContextHolder.getDataSourceType(); } }
@Slf4j @Configuration @AllArgsConstructor public class DynamicDataSourceConfig implements TransactionManagementConfigurer { private final Map<Object, Object> dataSourceMap = new HashMap<>(8); private final DataSourceProperties dataSourceProperties; @Bean("dynamicDataSource") public DynamicDataSource dataSource() { JdbcTemplate(dds).queryForList(DataSourceConstant.QUERY_DS_SQL); log.info("開始 -> 初始化動態數據源"); Optional.of(dbList).ifPresent(list -> list.forEach(db -> { log.info("數據源:{}", db.get(DataSourceConstant.DS_NAME)); HikariDataSource ds = new HikariDataSource(); dataSourceMap.put(db.get(DataSourceConstant.DS_ROUTE_KEY), ds); })); DynamicDataSource ds = new DynamicDataSource(); ds.setTargetDataSources(dataSourceMap); return ds; } @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return txManager(); } }
只須要根據用戶前臺選擇的數據源key ,在業務類保存到TTL 便可,會自動根據選擇路由數據源spring
DynamicDataSourceContextHolder.setDataSourceType(key)
這裏固然也能夠根據AOP 自定義註解等實現。數據庫
上邊其實已經完成了 咱們想要的需求功能,可是有什麼問題呢?
咱們在數據源管理面維護了數據源,動態去修改這個 dataSourceMap 實際上是無效的,不能作到實時刷新框架
咱們來看下 AbstractRoutingDataSource 的加載map 數據源的源碼,只有在初始化的時候調用 afterPropertiesSet 去初始數據源map.ide
那咱們只要獲取當前的DynamicDataSource bean 手動調用afterPropertiesSet 便可。 整個代碼以下微服務
public class DynamicDataSourceConfig implements TransactionManagementConfigurer { private final Map<Object, Object> dataSourceMap = new HashMap<>(8); private final DataSourceProperties dataSourceProperties; private final StringEncryptor stringEncryptor; @Bean("dynamicDataSource") public DynamicDataSource dataSource() { DynamicDataSource ds = new DynamicDataSource(); HikariDataSource cads = new HikariDataSource(); cads.setJdbcUrl(dataSourceProperties.getUrl()); cads.setDriverClassName(dataSourceProperties.getDriverClassName()); cads.setUsername(dataSourceProperties.getUsername()); cads.setPassword(dataSourceProperties.getPassword()); ds.setDefaultTargetDataSource(cads); dataSourceMap.put(0, cads); ds.setTargetDataSources(dataSourceMap); return ds; } /** * 組裝默認配置的數據源,查詢數據庫配置 */ @PostConstruct public void init() { DriverManagerDataSource dds = new DriverManagerDataSource(); dds.setUrl(dataSourceProperties.getUrl()); dds.setDriverClassName(dataSourceProperties.getDriverClassName()); dds.setUsername(dataSourceProperties.getUsername()); dds.setPassword(dataSourceProperties.getPassword()); List<Map<String, Object>> dbList = new JdbcTemplate(dds).queryForList(DataSourceConstant.QUERY_DS_SQL); log.info("開始 -> 初始化動態數據源"); Optional.of(dbList).ifPresent(list -> list.forEach(db -> { log.info("數據源:{}", db.get(DataSourceConstant.DS_NAME)); HikariDataSource ds = new HikariDataSource(); ds.setJdbcUrl(String.valueOf(db.get(DataSourceConstant.DS_JDBC_URL))); ds.setDriverClassName(Driver.class.getName()); ds.setUsername((String) db.get(DataSourceConstant.DS_USER_NAME)); String decPwd = stringEncryptor.decrypt((String) db.get(DataSourceConstant.DS_USER_PWD)); ds.setPassword(decPwd); dataSourceMap.put(db.get(DataSourceConstant.DS_ROUTE_KEY), ds); })); log.info("完畢 -> 初始化動態數據源,共計 {} 條", dataSourceMap.size()); } /** * 從新加載數據源配置 */ public Boolean reload() { init(); DynamicDataSource dataSource = dataSource(); dataSource.setTargetDataSources(dataSourceMap); dataSource.afterPropertiesSet(); return Boolean.FALSE; } @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return txManager(); }
歡迎關注咱們得到更多的好玩JavaEE實踐this