多數(shù)據(jù)源切換
db.properties
#MySQLjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&characterEncoding=utf-8jdbc.username=rootjdbc.password=admin#定義初始連接數(shù)initialSize=0#定義最大連接數(shù)maxActive=1000#定義最大空閑maxIdle=20#定義最小空閑minIdle=1#定義最長(zhǎng)等待時(shí)間maxWait=60000#MySQL# driverClassName 根據(jù)url自動(dòng)識(shí)別 這一項(xiàng)可配可不配,如果不配置druid會(huì)根據(jù)url自動(dòng)識(shí)別dbType,然后選擇相應(yīng)的driverClassNamejdbc.driver1=com.mysql.jdbc.Driverjdbc.url1=jdbc:mysql://localhost:3306/test1?allowMultiQueries=true&autoReconnect=true&characterEncoding=utf-8jdbc.username1=rootjdbc.password1=admin# 初始化時(shí)建立物理連接的個(gè)數(shù)。初始化發(fā)生在顯示調(diào)用init方法,或者第一次getConnection時(shí)initialSize1=0# 最大連接池?cái)?shù)量maxActive1=1000#定義最小空閑minIdle1=1# 獲取連接時(shí)最大等待時(shí)間,單位毫秒。配置了maxWait之后, # 缺省啟用公平鎖,并發(fā)效率會(huì)有所下降, # 如果需要可以通過配置useUnfairLock屬性為true使用非公平鎖。maxWait1=60000# druid 監(jiān)控# 屬性類型是字符串,通過別名的方式配置擴(kuò)展插件, # 常用的插件有: # 監(jiān)控統(tǒng)計(jì)用的filter:stat # 日志用的filter:log4j # 防御sql注入的filter:wallfilters1=stat,log4j# 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒timeBetweenEvictionRunsMillis1=60000# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒minEvictableIdleTimeMillis1=300000# 建議配置為true,不影響性能,并且保證安全性。 # 申請(qǐng)連接的時(shí)候檢測(cè),如果空閑時(shí)間大于 # timeBetweenEvictionRunsMillis, # 執(zhí)行validationQuery檢測(cè)連接是否有效。testWhileIdle1=true# 申請(qǐng)連接時(shí)執(zhí)行validationQuery檢測(cè)連接是否有效,做了這個(gè)配置會(huì)降低性能。testOnBorrow1=false# 歸還連接時(shí)執(zhí)行validationQuery檢測(cè)連接是否有效,做了這個(gè)配置會(huì)降低性能testOnReturn1=false# 是否緩存preparedStatement,也就是PSCache。# PSCache對(duì)支持游標(biāo)的數(shù)據(jù)庫(kù)性能提升巨大,比如說oracle。 # 在mysql5.5以下的版本中沒有PSCache功能,建議關(guān)閉掉。# 作者在5.5版本中使用PSCache,通過監(jiān)控界面發(fā)現(xiàn)PSCache有緩存命中率記錄, # 該應(yīng)該是支持PSCache。poolPreparedStatements1=false# 要啟用PSCache,必須配置大于0,當(dāng)大于0時(shí), # poolPreparedStatements自動(dòng)觸發(fā)修改為true。 # 在Druid中,不會(huì)存在Oracle下PSCache占用內(nèi)存過多的問題, # 可以把這個(gè)數(shù)值配置大一些,比如說100maxOpenPreparedStatements1=-1
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:websocket="http://www.springframework.org/schema/websocket" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd"> <!-- spring使用注解 配置掃描 com.ys下的掃描 但是在springmvc里邊已經(jīng)掃描一次了 這時(shí)就要加上屬性 use-default-filters="true" 這個(gè)屬性就是使用默認(rèn)的掃描 默認(rèn)就掃描com.ys下所有 設(shè)置為false 在下邊配置需要掃描的部分--> <!-- 現(xiàn)在的配置就只會(huì)掃描帶@Service和@Repository注解的類 --> <context:component-scan base-package="com" use-default-filters="false"> <!-- org.springframework.stereotype.Service就是注解@service 這個(gè)注解使用在service里 所以就是掃描service包 org.springframework.stereotype.Repository Repository倉(cāng)庫(kù)--> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.beans.factory.annotation.Autowired"/> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan> <!-- 讀取properties文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:db.properties</value> </list> </property> </bean> <!-- 配置連接池?cái)?shù)據(jù)源 文檔搜索BasicDataSource --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- results in a setDriverClassName(String) call --> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 初始化連接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 連接池最大數(shù)量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 連接池最大空閑 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 連接池最小空閑 --> <property name="minIdle" value="${minIdle}"></property> <!-- 獲取連接最大等待時(shí)間 --> <property name="maxWait" value="${maxWait}"></property> </bean> <bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="${jdbc.url1}" /> <property name="username" value="${jdbc.username1}" /> <property name="password" value="${jdbc.password1}" /> <property name="driverClassName" value="${jdbc.driver1}" /> <!-- 初始化連接大小 --> <property name="initialSize" value="${initialSize1}"/> <!-- 最小空閑 --> <property name="minIdle" value="${minIdle1}" /> <!-- 最大連接池?cái)?shù)量 --> <property name="maxActive" value="${maxActive1}" /> <!-- 獲取連接最大等待時(shí)間 --> <property name="maxWait" value="${maxWait1}"/> <!-- 監(jiān)控統(tǒng)計(jì)用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall --> <property name="filters" value="${filters1}" /> <!-- 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis1}" /> <!-- 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis1}" /> <!-- 建議配置為true,不影響性能,并且保證安全性。 申請(qǐng)連接的時(shí)候檢測(cè) --> <property name="testWhileIdle" value="${testWhileIdle1}"/> <!-- 申請(qǐng)連接時(shí)執(zhí)行validationQuery檢測(cè)連接是否有效,做了這個(gè)配置會(huì)降低性能。 --> <property name="testOnBorrow" value="${testOnBorrow1}"/> <!-- 歸還連接時(shí)執(zhí)行validationQuery檢測(cè)連接是否有效,做了這個(gè)配置會(huì)降低性能 --> <property name="testOnReturn" value="false" /> <!-- 是否緩存preparedStatement,也就是PSCache 適用支持游標(biāo)的數(shù)據(jù)庫(kù) 如Oracle --> <property name="poolPreparedStatements" value="${poolPreparedStatements1}"/> <!-- 要啟用PSCache,必須配置大于0,當(dāng)大于0時(shí) poolPreparedStatements自動(dòng)觸發(fā)修改為true。 --> <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements1}"/> <!-- 定義監(jiān)控日志輸出間隔 --> <property name="timeBetweenLogStatsMillis" value="60000"/> <!--<property name="statLogger" ref ="statLoggerb"/> --> <!-- 若需要mybatis的批量sql需配置 不配置則報(bào)錯(cuò):nested exception is java.sql.SQLException: sql injection violation, multi-statement not allow--> <property name="proxyFilters" ref="wall-filter"/> </bean> <!-- 若需要mybatis的批量sql需配置 --> <bean id="wall-filter" class="com.alibaba.druid.wall.WallFilter"> <property name="config" ref="wall-config" /> </bean> <bean id="wall-config" class="com.alibaba.druid.wall.WallConfig"> <property name="multiStatementAllow" value="true" /> </bean> <!-- 多數(shù)據(jù)源配置 --> <bean id="multipleDataSource" class="com.ys.dbConfig.MultipleDataSource"> <!-- 默認(rèn)數(shù)據(jù)源 --> <property name="defaultTargetDataSource" ref="dataSource" /> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="dataSource" value-ref="dataSource"/> <entry key="dataSource1" value-ref="dataSource1"/> </map> </property> </bean> <!-- 配置 sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 數(shù)據(jù)庫(kù)連接池 --> <property name="dataSource" ref="multipleDataSource"/> <property name="configLocation" value="classpath:mybatis.cfg.xml"/> <!-- 加載Mybatis全局配置文件 --> <property name="mapperLocations" value="classpath:com/ys/mapper/*.xml"/> </bean> <!-- 掃描的dao包(映射文件) 本身應(yīng)該在mybatis里 現(xiàn)在交給spring --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ys.dao"/> </bean><!-- 事務(wù)配置 --> <!-- 配置事務(wù)管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="multipleDataSource"></property> </bean> <!-- 開啟注解事務(wù) 引用transactionManager --> <tx:annotation-driven transaction-manager="transactionManager"/></beans>創(chuàng)建MultipleDataSource.java
package com.ys.dbConfig;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class MultipleDataSource extends AbstractRoutingDataSource{ @Override protected Object determineCurrentLookupKey() { return MultipleDataSourceHandler.getRouteKey(); }}創(chuàng)建MultipleDataSourceHandler.java
package com.ys.dbConfig; /** *@ Title MultipleDataSourceHandler.java *@ description: 多數(shù)據(jù)源Handler*@ time 創(chuàng)建時(shí)間:2018年8月25日 上午10:52:12 **/public class MultipleDataSourceHandler { private static ThreadLocal<String> routeKey = new ThreadLocal<String>(); /** * @Title: getRouteKey * @Description: 獲取當(dāng)前線程的數(shù)據(jù)源路由的key * @param @return * @return String * @date createTime:2018年8月27日上午10:34:52 */ public static String getRouteKey(){ return routeKey.get(); } /** * @Title: setRouteKey * @Description: 綁定當(dāng)前線程數(shù)據(jù)源路由的key 使用完成后必須調(diào)用removeRouteKey()方法刪除 * @param @param key * @return void * @date createTime:2018年8月27日上午10:35:03 */ public static void setRouteKey(String key){ routeKey.set(key); } /** * @Title: removeRouteKey * @Description: 刪除與當(dāng)前線程綁定的數(shù)據(jù)源路由的key * @return void * @date createTime:2018年8月27日上午10:35:31 */ public static void removeRouteKey(){ routeKey.remove(); }}切換數(shù)據(jù)源
MultipleDataSourceHandler.setRouteKey(“dataSource1”);
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)VeVb武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選