基于spring的動態數據源
項目過程中遇到這樣一個需求,系統啟動后動態設置數據源,不同用戶登錄系統后訪問的數據庫不同。
好在所有書庫結構一致。
用spring 的AbstractRoutingDataSource解決了這個問題。
原理如圖:

項目采用的是hibernate,直接在spring.xml設置sessionFactory的dataSource屬性為動態數據源即可。
因為項目所有數據庫結構都一致,為了避免每次設置數據源的時候要改一堆參數,修改了spring AbstractRoutingDataSource類增加了一個getTargetDataSources方法,獲取當前數據源詳細信息,在其基礎上修改數據庫名稱、用戶名、密碼即可,不用每次設置一堆參數。
Map<String,ComboPooledDataSource> targetDataSources=dynamicDataSource.getTargetDataSources();

if(targetDataSources==null)
{
targetDataSources=new HashMap<String, ComboPooledDataSource>();
targetDataSources.put("baseDataSource", baseDataSource);
}
targetDataSources.put(dataSourceName, subSystemDataSource);
dynamicDataSource.setTargetDataSources(targetDataSources);
dynamicDataSource.afterPropertiesSet();另外,設置AbstractRoutingDataSource參數后要調用afterPropertiesSet()方法,spring容器才會進行加載操作。
在動態設置數據源方面,可以通過兩種方式實現:
1.在action(項目使用struts)中進行設置,可以確保在每個servlet線程中數據源是一致的。
2.以aop方式,對service方法進行攔截,根據需求設置不同數據源。