Spring配置多數(shù)據(jù)源切換
多數(shù)據(jù)源切換
db.properties
#MySQL jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&characterEncoding=utf-8 jdbc.username=root jdbc.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)的driverClassName jdbc.driver1=com.mysql.jdbc.Driver jdbc.url1=jdbc:mysql://localhost:3306/test1?allowMultiQueries=true&autoReconnect=true&characterEncoding=utf-8 jdbc.username1=root jdbc.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ì)有所下降, # 如果需要可以通過(guò)配置useUnfairLock屬性為true使用非公平鎖。 maxWait1=60000 # druid 監(jiān)控 # 屬性類(lèi)型是字符串,通過(guò)別名的方式配置擴(kuò)展插件, # 常用的插件有: # 監(jiān)控統(tǒng)計(jì)用的filter:stat # 日志用的filter:log4j # 防御sql注入的filter:wall filters1=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ù)性能提升巨大,比如說(shuō)oracle。 # 在mysql5.5以下的版本中沒(méi)有PSCache功能,建議關(guān)閉掉。 # 作者在5.5版本中使用PSCache,通過(guò)監(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)存過(guò)多的問(wèn)題, # 可以把這個(gè)數(shù)值配置大一些,比如說(shuō)100 maxOpenPreparedStatements1=-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注解的類(lèi) --> <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> <!-- 開(kāi)啟注解事務(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ì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
- springboot集成@DS注解實(shí)現(xiàn)數(shù)據(jù)源切換的方法示例
- springboot+dynamicDataSource動(dòng)態(tài)添加切換數(shù)據(jù)源方式
- SpringBoot?+DynamicDataSource切換多數(shù)據(jù)源的全過(guò)程
- Springboot實(shí)現(xiàn)根據(jù)用戶ID切換動(dòng)態(tài)數(shù)據(jù)源
- Springboot動(dòng)態(tài)切換數(shù)據(jù)源的具體實(shí)現(xiàn)與原理分析
- 詳細(xì)聊聊SpringBoot中動(dòng)態(tài)切換數(shù)據(jù)源的方法
- SpringBoot AOP方式實(shí)現(xiàn)多數(shù)據(jù)源切換的方法
- Spring配置多個(gè)數(shù)據(jù)源并實(shí)現(xiàn)數(shù)據(jù)源的動(dòng)態(tài)切換功能
相關(guān)文章
詳解在Spring Boot中使用數(shù)據(jù)庫(kù)事務(wù)
本篇文章主要介紹了詳解在Spring Boot中使用數(shù)據(jù)庫(kù)事務(wù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05詳解JDBC對(duì)Mysql utf8mb4字符集的處理
這篇文章主要介紹了詳解JDBC對(duì)Mysql utf8mb4字符集的處理,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-11-11一小時(shí)迅速入門(mén)Mybatis之初識(shí)篇
這篇文章主要介紹了迅速入門(mén)Mybatis之初識(shí)篇,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09springboot使用jasypt加密庫(kù)實(shí)現(xiàn)數(shù)據(jù)庫(kù)加解密示例代碼
這篇文章主要給大家介紹了關(guān)于springboot使用jasypt加密庫(kù)實(shí)現(xiàn)數(shù)據(jù)庫(kù)加解密的相關(guān)資料,Jasypt是一個(gè)用于配置文件加密的Java庫(kù),它可以用來(lái)加密和解密配置文件中的敏感信息,如數(shù)據(jù)庫(kù)密碼、API?密鑰等,需要的朋友可以參考下2024-04-04基于Java實(shí)現(xiàn)五子棋小游戲(附源碼)
這篇文章主要為大家介紹了如何通過(guò)Java實(shí)現(xiàn)簡(jiǎn)單的五子棋游戲,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Java游戲開(kāi)發(fā)有一定幫助,需要的可以參考一下2022-11-11Java泛型extends關(guān)鍵字設(shè)置邊界的實(shí)現(xiàn)
這篇文章主要介紹了Java泛型extends關(guān)鍵字設(shè)置邊界的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09200行Java代碼編寫(xiě)一個(gè)計(jì)算器程序
本篇文章給大家分享的只用200行java代碼,實(shí)現(xiàn)一個(gè)計(jì)算器程序,不僅能夠計(jì)算加減乘除,還能夠匹配小括號(hào)。實(shí)現(xiàn)代碼超簡(jiǎn)單,需要的朋友參考下吧2017-12-12Spring中ClassPathXmlApplicationContext類(lèi)的使用詳解
這篇文章主要介紹了Spring中ClassPathXmlApplicationContext類(lèi)的使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01