項目中有用到多數據源,並進行動態切換,使用的是阿里的druid。看網上有一篇大致一樣的就偷偷懶
import java.sql.SQLFeatureNotSupportedException; import java.util.Map; import com.alibaba.druid.pool.DruidDataSource; import org.apache.log4j.Logger; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import com.xyh.util.SpringUtils; /** * @author yuanhao * @describe 實現動態數據源切換邏輯 */ public class DataSourceUtil extends AbstractRoutingDataSource { private Logger log = Logger.getLogger(this.getClass()); /** * 數據源資源池 */ private Map<Object, Object> _targetDataSources; /** * 數據源名稱 */ /** * @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey() * @describe 數據源為空或者為0時,自動切換至默認數據源 */ @Override protected Object determineCurrentLookupKey() { String dataSourceName = DBContextHolder.getDataSource(); try { if (dataSourceName == null || "".equals(dataSourceName)) {// 如果傳入數據源id為空 throw new Exception("傳入的數據源名稱為空,無法選擇數據源"); } this.selectDataSource(dataSourceName); } catch (Exception e) { e.printStackTrace(); } log.debug("--------> use datasource " + dataSourceName); return dataSourceName; } /** * @param key * 數據源id * @throws Exception * @describe 數據源存在連接池中時不做處理, 不存在將新數據鏈接添加至連接池 * / public void selectDataSource(String dataSourceName) throws Exception { Object obj = this._targetDataSources.get(dataSourceName); // 如果數據源已經有了 if (obj != null) { return; } else {// 如果沒有則從spring容器中獲取 DruidDataSource dataSource = (DruidDataSource) SpringUtils .getBeanInstance(dataSourceName); if (dataSource != null) this.setDataSource(dataSourceName, dataSource); else { throw new Exception("無法取得數據庫連接配置,請核對是否已經配置"); } } } /** * 將數據源寫入池中 * @param key * @param dataSource */ private void setDataSource(String dataSourceName, DruidDataSource dataSource) { //this.addTargetDataSource(dataSourceName, dataSource); this._targetDataSources.put(dataSourceName, dataSource); this.setTargetDataSources(this._targetDataSources); } @SuppressWarnings({ "unchecked", "rawtypes" }) public void setTargetDataSources(Map targetDataSources) { this._targetDataSources = targetDataSources; super.setTargetDataSources(this._targetDataSources); afterPropertiesSet(); } /* public void addTargetDataSource(String key, DruidDataSource dataSource) { }*/ /** * @return * @throws SQLFeatureNotSupportedException */ public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { // TODO Auto-generated method stub return null; } }
數據源選擇工具類
public class DBContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); /** * 傳入數據源名稱 * * @param key */ public static void setDataSource(String key) { contextHolder.set(key); } /** * 取數據源名稱 * * @return */ public static String getDataSource() { return contextHolder.get(); } /** * 銷毀數據源名稱 * * @return */ public static void clearDataSource() { contextHolder.remove(); } }
pring 配置:
<!--db1--> <bean id="dataSource411602" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" lazy-init="true"> <property name="driverClassName"> <value>${jdbc.oracle.driverClassName}</value> </property> <property name="url"> <value>jdbc:oracle:thin:@192.168.0.1:20003:orcl</value> </property> <property name="username"> <value>test</value> </property> <property name="password"> <value>test</value> </property> <property name="filters" value="stat"></property> </bean> <!--db2--> <bean id="dataSource411606" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" lazy-init="true"> <property name="driverClassName"> <value>${jdbc.oracle.driverClassName}</value> </property> <property name="url"> <value>jdbc:oracle:thin:@192.168.0.2:60021:orcl</value> </property> <property name="username"> <value>test</value> </property> <property name="password"> <value>test</value> </property> <property name="filters" value="stat"></property> </bean> <!--數據源--> <bean id="dataSource" class="com.xyh.util.dbutil.DataSourceUtil"> <property name="targetDataSources"> <map key-type="java.lang.String"> </map> </property> </bean> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocations"> <list> <value>classpath:sql-map-config.xml</value> </list> </property> <property name="dataSource" ref="dataSource" /> </bean> <!-- JDBC 事務管理 --> <bean id="jdbcTxManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean>
使用的時候只需要在要切換數據源的地方寫下以下代碼DBContextHolder.setDataSource(beanId);
數據源就自動切換成你想要使用的那個了!!!
---------------------
原文:https://blog.csdn.net/qq_15541045/article/details/78736526