1.创建jdbc.properties
#第一个数据源信息的
csjdbc.driver=oracle.jdbc.driver.OracleDriver
csjdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
csjdbc.username=oracle
csjdbc.password=oracle
#最大连接数
csjdbc.maxTotal=30
#最大空闲连接数
csjdbc.maxIdle=10
#初始化连接数
csjdbc.initialSize=5
#第二个数据源信息的
zsjdbc.driver=oracle.jdbc.driver.OracleDriver
zsjdbc.url=jdbc:oracle:thin:@localhost:1521:JZQHDATA
zsjdbc.username=oracle
zsjdbc.password=oracle
#最大连接数
zsjdbc.maxTotal=30
#最大空闲连接数
zsjdbc.maxIdle=10
#初始化连接数
zsjdbc.initialSize=5
2.获取当前使用的数据源
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* <p>desc:配置多个数据源 </p>
* <p>类名:DynamicDataSource </p>
* <p>创建时间:2021-3-23 上午9:38:42 </p>
* <p>@author:yy</p>
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
protected Object determineCurrentLookupKey() {
return DBContextHolder.getDbType();
}
}
3.切换数据源的工具类:
/**
* <p>desc: 数据源的切换</p>
* <p>类名:DBContextHolder </p>
* <p>创建时间:2021-3-1023 上午9:39:24 </p>
* <p>@author:yy</p>
*/
public class DBContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDbType(String dbType) {
contextHolder.set(dbType);
}
public static String getDbType() {
return ((String) contextHolder.get());
}
public static void clearDbType() {
contextHolder.remove();
}
}
4.在spring配置文件中进行配置
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 读取db.properties -->