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 #定義最長等待時間 maxWait=60000 #MySQL # driverClassName 根據(jù)url自動識別 這一項可配可不配,如果不配置druid會根據(jù)url自動識別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ù)。初始化發(fā)生在顯示調(diào)用init方法,或者第一次getConnection時 initialSize1=0 # 最大連接池數(shù)量 maxActive1=1000 #定義最小空閑 minIdle1=1 # 獲取連接時最大等待時間,單位毫秒。配置了maxWait之后, # 缺省啟用公平鎖,并發(fā)效率會有所下降, # 如果需要可以通過配置useUnfairLock屬性為true使用非公平鎖。 maxWait1=60000 # druid 監(jiān)控 # 屬性類型是字符串,通過別名的方式配置擴展插件, # 常用的插件有: # 監(jiān)控統(tǒng)計用的filter:stat # 日志用的filter:log4j # 防御sql注入的filter:wall filters1=stat,log4j # 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 timeBetweenEvictionRunsMillis1=60000 # 配置一個連接在池中最小生存的時間,單位是毫秒 minEvictableIdleTimeMillis1=300000 # 建議配置為true,不影響性能,并且保證安全性。 # 申請連接的時候檢測,如果空閑時間大于 # timeBetweenEvictionRunsMillis, # 執(zhí)行validationQuery檢測連接是否有效。 testWhileIdle1=true # 申請連接時執(zhí)行validationQuery檢測連接是否有效,做了這個配置會降低性能。 testOnBorrow1=false # 歸還連接時執(zhí)行validationQuery檢測連接是否有效,做了這個配置會降低性能 testOnReturn1=false # 是否緩存preparedStatement,也就是PSCache。 # PSCache對支持游標(biāo)的數(shù)據(jù)庫性能提升巨大,比如說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時, # poolPreparedStatements自動觸發(fā)修改為true。 # 在Druid中,不會存在Oracle下PSCache占用內(nèi)存過多的問題, # 可以把這個數(shù)值配置大一些,比如說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)掃描一次了 這時就要加上屬性 use-default-filters="true" 這個屬性就是使用默認(rèn)的掃描 默認(rèn)就掃描com.ys下所有 設(shè)置為false 在下邊配置需要掃描的部分--> <!-- 現(xiàn)在的配置就只會掃描帶@Service和@Repository注解的類 --> <context:component-scan base-package="com" use-default-filters="false"> <!-- org.springframework.stereotype.Service就是注解@service 這個注解使用在service里 所以就是掃描service包 org.springframework.stereotype.Repository Repository倉庫--> <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> <!-- 配置連接池數(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> <!-- 獲取連接最大等待時間 --> <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}" /> <!-- 最大連接池數(shù)量 --> <property name="maxActive" value="${maxActive1}" /> <!-- 獲取連接最大等待時間 --> <property name="maxWait" value="${maxWait1}"/> <!-- 監(jiān)控統(tǒng)計用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall --> <property name="filters" value="${filters1}" /> <!-- 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis1}" /> <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis1}" /> <!-- 建議配置為true,不影響性能,并且保證安全性。 申請連接的時候檢測 --> <property name="testWhileIdle" value="${testWhileIdle1}"/> <!-- 申請連接時執(zhí)行validationQuery檢測連接是否有效,做了這個配置會降低性能。 --> <property name="testOnBorrow" value="${testOnBorrow1}"/> <!-- 歸還連接時執(zhí)行validationQuery檢測連接是否有效,做了這個配置會降低性能 --> <property name="testOnReturn" value="false" /> <!-- 是否緩存preparedStatement,也就是PSCache 適用支持游標(biāo)的數(shù)據(jù)庫 如Oracle --> <property name="poolPreparedStatements" value="${poolPreparedStatements1}"/> <!-- 要啟用PSCache,必須配置大于0,當(dāng)大于0時 poolPreparedStatements自動觸發(fā)修改為true。 --> <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements1}"/> <!-- 定義監(jiān)控日志輸出間隔 --> <property name="timeBetweenLogStatsMillis" value="60000"/> <!--<property name="statLogger" ref ="statLoggerb"/> --> <!-- 若需要mybatis的批量sql需配置 不配置則報錯: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ù)庫連接池 --> <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)建時間: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é)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
- springboot集成@DS注解實現(xiàn)數(shù)據(jù)源切換的方法示例
- springboot+dynamicDataSource動態(tài)添加切換數(shù)據(jù)源方式
- SpringBoot?+DynamicDataSource切換多數(shù)據(jù)源的全過程
- Springboot實現(xiàn)根據(jù)用戶ID切換動態(tài)數(shù)據(jù)源
- Springboot動態(tài)切換數(shù)據(jù)源的具體實現(xiàn)與原理分析
- 詳細(xì)聊聊SpringBoot中動態(tài)切換數(shù)據(jù)源的方法
- SpringBoot AOP方式實現(xiàn)多數(shù)據(jù)源切換的方法
- Spring配置多個數(shù)據(jù)源并實現(xiàn)數(shù)據(jù)源的動態(tài)切換功能
相關(guān)文章
詳解在Spring Boot中使用數(shù)據(jù)庫事務(wù)
本篇文章主要介紹了詳解在Spring Boot中使用數(shù)據(jù)庫事務(wù),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05springboot使用jasypt加密庫實現(xiàn)數(shù)據(jù)庫加解密示例代碼
這篇文章主要給大家介紹了關(guān)于springboot使用jasypt加密庫實現(xiàn)數(shù)據(jù)庫加解密的相關(guān)資料,Jasypt是一個用于配置文件加密的Java庫,它可以用來加密和解密配置文件中的敏感信息,如數(shù)據(jù)庫密碼、API?密鑰等,需要的朋友可以參考下2024-04-04Java泛型extends關(guān)鍵字設(shè)置邊界的實現(xiàn)
這篇文章主要介紹了Java泛型extends關(guān)鍵字設(shè)置邊界的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Spring中ClassPathXmlApplicationContext類的使用詳解
這篇文章主要介紹了Spring中ClassPathXmlApplicationContext類的使用詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01