第一步:在pom.xml檔案中引入依賴
<!--配置多資料源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.1.1</version>
<scope>compile</scope>
</dependency>
<!-- 資料連接配接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
第二步:在bootstrap.yml檔案或application.properties檔案中添加配置,我這裡的druid就簡單的配置了一下,做的全局配置,也可以分别單獨給資料源做配置,這裡就不做示範了
spring:
datasource:
druid:
stat-view-servlet:
enabled: true
# 禁用HTML頁面上的“Reset All”功能
reset-enable: false
# 登入名
login-username: admin
# 登入密碼
login-password: 123456
dynamic:
# 全局配置
druid:
filters: stat # 啟用内置過濾器(stat必須,否則監控不到SQL)
# 配置初始化大小、最小、最大
initial-size: 5
min-idle: 5
keep-alive: true
#測試連接配接間隔為55s
time-between-eviction-runs-millis: 55000
primary: mysql
strict: false
datasource:
mysql:
url: jdbc:mysql://ip:3306/users?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
username: admin
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
oracle:
username: admin
password: 123
url: jdbc:oracle:thin:@192.112.50.42:1521:test
driver-class-name: oracle.jdbc.driver.OracleDriver
第三步:這個很關鍵,需要在啟動類中配置
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
否則會報以下異常:
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (the profiles dev are currently active).