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" 這個屬性就是使用默認的掃描
默認就掃描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">
<!-- 默認數(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)鏈接
- Spring Boot 動態(tài)數(shù)據(jù)源示例(多數(shù)據(jù)源自動切換)
- Springboot如何設(shè)置多數(shù)據(jù)源,隨時切換
- SpringBoot AOP方式實現(xiàn)多數(shù)據(jù)源切換的方法
- Spring實現(xiàn)動態(tài)切換多數(shù)據(jù)源的解決方案
- spring boot+mybatis 多數(shù)據(jù)源切換(實例講解)
- Spring整合多數(shù)據(jù)源實現(xiàn)動態(tài)切換的實例講解
- 詳解Spring多數(shù)據(jù)源如何切換
- Spring通過攔截器實現(xiàn)多數(shù)據(jù)源切換的示例代碼
相關(guān)文章
SSO單點登錄系統(tǒng)實現(xiàn)原理及流程圖解
這篇文章主要介紹了SSO單點登錄系統(tǒng)實現(xiàn)原理及流程圖解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-12-12
java同步器AQS架構(gòu)AbstractQueuedSynchronizer原理解析下
這篇文章主要為大家介紹了java同步器AQS架構(gòu)AbstractQueuedSynchronizer原理解析下,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-03-03
Java Spring5學(xué)習(xí)之JdbcTemplate詳解
這篇文章主要介紹了Java Spring5學(xué)習(xí)之JdbcTemplate詳解,文中有非常詳細的代碼示例,對正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-05-05
spring?cloud?配置阿里數(shù)據(jù)庫連接池?druid的示例代碼
這篇文章主要介紹了spring?cloud?配置阿里數(shù)據(jù)庫連接池?druid,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03
使用SpringBoot創(chuàng)建一個RESTful API的詳細步驟
使用 Java 的 Spring Boot 創(chuàng)建 RESTful API 可以滿足多種開發(fā)場景,它提供了快速開發(fā)、易于配置、可擴展、可維護的優(yōu)點,尤其適合現(xiàn)代軟件開發(fā)的需求,幫助你快速構(gòu)建出高性能的后端服務(wù),需要的朋友可以參考下2025-01-01
實例講解分布式緩存軟件Memcached的Java客戶端使用
這篇文章主要介紹了分布式緩存軟件Memcached的Java客戶端使用,Memcached在GitHub上開源,作者用其Windows平臺下的版本進行演示,需要的朋友可以參考下2016-01-01

