數據源鏈接池使用druid 其餘的數據源基本原理相同java
spring中配置默認數據源鏈接池以下:spring
<!-- 數據源配置, 使用 BoneCP 數據庫鏈接池 --> <bean id="dataSourceOne" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="name" value="dataSourceOne"/> <!-- 數據源驅動類可不寫,Druid默認會自動根據URL識別DriverClass --> <property name="driverClassName" value="${jdbc.driver}" /> <!-- 基本屬性 url、user、password --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="${jdbc.pool.init}" /> <property name="minIdle" value="${jdbc.pool.minIdle}" /> <property name="maxActive" value="${jdbc.pool.maxActive}" /> <!-- 配置獲取鏈接等待超時的時間 --> <property name="maxWait" value="60000" /> <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="${jdbc.testSql}" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打開PSCache,而且指定每一個鏈接上PSCache的大小(Oracle使用) <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> --> <!-- 配置監控統計攔截的filters --> <property name="filters" value="stat" /> </bean>
接下來配置多數據源beansql
<!-- 多數據源配置 --> <bean id="dynamicDataSource" class="com.XXX.datasource.DynamicDataSource" > <property name="targetDataSources"> <map> <entry value-ref="dataSourceOne" key="dataSourceOne"></entry> <!--此處是對數據源的引用--> <!-- <entry value-ref="dataSourceTow" key="dataSourceTow"></entry> --> </map> </property> <property name="defaultTargetDataSource" ref="dataSourceOne" /> <property name="debug" value="true"/> </bean>
這個類 com.XXX.datasource.DynamicDataSource 須要手動建立數據庫
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import org.springframework.util.StringUtils; import com.alibaba.druid.pool.DruidConnectionHolder; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alibaba.druid.pool.DruidPooledConnection; import com.alibaba.druid.stat.DruidDataSourceStatManager; import com.alibaba.druid.util.DruidDataSourceUtils; /** * @author zh */ public class DynamicDataSource extends AbstractRoutingDataSource{ private boolean debug = false; Logger log = LoggerFactory.getLogger(this.getClass()); private Map<Object, Object> dynamicTargetDataSources; private Object dynamicDefaultTargetDataSource; /* (non-Javadoc) @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey() */ @Override protected Object determineCurrentLookupKey() { String datasource=DBContextHolder.getDataSource(); if(debug) { if(StringUtils.isEmpty(datasource)){ log.info("---當前數據源:默認數據源---"); }else{ log.info("---當前數據源:"+datasource+"---"); } } return datasource; } @Override public void setTargetDataSources(Map<Object, Object> targetDataSources) { super.setTargetDataSources(targetDataSources); this.dynamicTargetDataSources = targetDataSources; } //建立數據源 public boolean createDataSource(String key,String driveClass,String url,String username,String password){ try { try { //排除鏈接不上的錯誤 Class.forName(driveClass); DriverManager.getConnection(url, username, password); } catch (Exception e) { return false; } @SuppressWarnings("resource") DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setName(key); druidDataSource.setDriverClassName(driveClass); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); druidDataSource.setMaxWait(60000); druidDataSource.setFilters("stat"); DataSource createDataSource = (DataSource)druidDataSource; druidDataSource.init(); Map<Object, Object> dynamicTargetDataSources2 = this.dynamicTargetDataSources; dynamicTargetDataSources2.put(key, createDataSource);//加入map setTargetDataSources(dynamicTargetDataSources2);//將map賦值給父類的TargetDataSources super.afterPropertiesSet();//將TargetDataSources中的鏈接信息放入resolvedDataSources管理 return true; } catch (Exception e) { log.error(e+""); return false; } } //刪除數據源 public boolean delDatasources(String datasourceid){ Map<Object, Object> dynamicTargetDataSources2 = this.dynamicTargetDataSources; if(dynamicTargetDataSources2.containsKey(datasourceid)){ Set<DruidDataSource> druidDataSourceInstances = DruidDataSourceStatManager.getDruidDataSourceInstances(); for(DruidDataSource l:druidDataSourceInstances){ if(datasourceid.equals(l.getName())){ System.out.println(l); dynamicTargetDataSources2.remove(datasourceid); DruidDataSourceStatManager.removeDataSource(l); setTargetDataSources(dynamicTargetDataSources2);//將map賦值給父類的TargetDataSources super.afterPropertiesSet();//將TargetDataSources中的鏈接信息放入resolvedDataSources管理 return true; } } return false; }else{ return false; } } //測試數據源鏈接是否有效 public boolean testDatasource(String key,String driveClass,String url,String username,String password){ try { Class.forName(driveClass); DriverManager.getConnection(url, username, password); return true; } catch (Exception e) { return false; } } /** * Specify the default target DataSource, if any. * <p>The mapped value can either be a corresponding {@link javax.sql.DataSource} * instance or a data source name String (to be resolved via a * {@link #setDataSourceLookup DataSourceLookup}). * <p>This DataSource will be used as target if none of the keyed * {@link #setTargetDataSources targetDataSources} match the * {@link #determineCurrentLookupKey()} current lookup key. */ public void setDefaultTargetDataSource(Object defaultTargetDataSource) { super.setDefaultTargetDataSource(defaultTargetDataSource); this.dynamicDefaultTargetDataSource = defaultTargetDataSource; } /** * @param debug the debug to set */ public void setDebug(boolean debug) { this.debug = debug; } /** * @return the debug */ public boolean isDebug() { return debug; } /** * @return the dynamicTargetDataSources */ public Map<Object, Object> getDynamicTargetDataSources() { return dynamicTargetDataSources; } /** * @param dynamicTargetDataSources the dynamicTargetDataSources to set */ public void setDynamicTargetDataSources( Map<Object, Object> dynamicTargetDataSources) { this.dynamicTargetDataSources = dynamicTargetDataSources; } /** * @return the dynamicDefaultTargetDataSource */ public Object getDynamicDefaultTargetDataSource() { return dynamicDefaultTargetDataSource; } /** * @param dynamicDefaultTargetDataSource the dynamicDefaultTargetDataSource to set */ public void setDynamicDefaultTargetDataSource( Object dynamicDefaultTargetDataSource) { this.dynamicDefaultTargetDataSource = dynamicDefaultTargetDataSource; } }
其中該類繼承了spring的AbstractRoutingDataSource 查看其源碼,發現全部的數據源都是經過app
afterPropertiesSet() 將存放在targetDataSources 這個Map中的數據源賦值給resolvedDataSourceside
對象的,spring是從resolvedDataSources對象中獲取數據源對象的,咱們能須要把本身的數據源放入工具
resolvedDataSources這個Map中就ok了。測試
接下來建立數據源切換工具類ui
/** * 數據源切換 * @author zh * */ public class DBContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); //調用此方法,切換數據源 public static void setDataSource(String dataSource) { contextHolder.set(dataSource); } public static String getDataSource() { return contextHolder.get(); } public static void clearDataSource() { contextHolder.remove(); } }
具體實動態新增數據源,須要建立數據庫用以存儲 數據庫鏈接信息,以及數據源key信息。this
初始話數據庫鏈接數據源,能夠使用spring監聽 實現ApplicationListener便可,以下
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import com.casking.cdds.modules.datasource.entity.CNDatasources; public class InitDatasourcesLS implements ApplicationListener<ApplicationEvent>{ @Autowired private CNDatasourcesService service; @Override public void onApplicationEvent(ApplicationEvent event) { List<CNDatasources> list = service.findList(new CNDatasources()); for(CNDatasources li:list){ //這裏調用建立數據源的方法便可 service.addDataSourceDynamic(li.getDatasource(),li); } } }