SpringBoot使用druid配置多數(shù)據(jù)源問題
一、背景
使用spring boot配置多數(shù)據(jù)源,數(shù)據(jù)源分別為postgresql、mysql
二、版本介紹
- spring boot——2.5.4
- druid——1.2.11
- postgresql——12
- mysql——8.0.16
- maven——3.0
- idea——2019
三、項目結(jié)構(gòu)
java package目錄

resource目錄存放mapper.xml文件,按照數(shù)據(jù)源創(chuàng)建package

四、maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- MySql驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>五、yaml配置文件
server:
port: 8081
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
web-stat-filter:
enabled: true #是否啟用StatFilter默認(rèn)值true
url-pattern: /*
exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
session-stat-enable: true
session-stat-max-count: 10
stat-view-servlet:
enabled: true #是否啟用StatViewServlet默認(rèn)值true
url-pattern: /druid/*
reset-enable: true
login-username: admin
login-password: admin
allow:
db1:
username: postgres
password: localhost
url: jdbc:postgresql://localhost:5432/test
driver-class-name: org.postgresql.Driver
initial-size: 5 # 初始化大小
min-idle: 5 # 最小
max-active: 100 # 最大
max-wait: 60000 # 配置獲取連接等待超時的時間
validation-query: select version()
time-between-eviction-runs-millis: 60000 # 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
min-evictable-idle-time-millis: 300000 # 指定一個空閑連接最少空閑多久后可被清除,單位是毫秒
filters: config,wall,stat # 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計,'wall'用于防火墻
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=false
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否緩存preparedStatement,也就是PSCache 官方建議MySQL下建議關(guān)閉 個人建議如果想用SQL防火墻 建議打開
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
db2:
username: root
password: localhost
url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
initial-size: 5 # 初始化大小
min-idle: 5 # 最小
max-active: 100 # 最大
max-wait: 60000 # 配置獲取連接等待超時的時間
validation-query: select 'x'
time-between-eviction-runs-millis: 60000 # 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
min-evictable-idle-time-millis: 300000 # 指定一個空閑連接最少空閑多久后可被清除,單位是毫秒
filters: config,wall,stat # 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計,'wall'用于防火墻
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=false
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否緩存preparedStatement,也就是PSCache 官方建議MySQL下建議關(guān)閉 個人建議如果想用SQL防火墻 建議打開
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
mybatis:
mapper-locations: classpath:com/demo/mapper/*.xml
type-aliases-package: com.demo.entity
configuration:
log-impl:
mapUnderscoreToCamelCase: true
#showSql
logging:
level:
java.sql: debug
org.apache.ibatis: debug
com.demo.mapper: debug
config: classpath:logback-spring.xml六、數(shù)據(jù)源配置文件
@Configuration
@MapperScan(basePackages = "com.demo.mapper.postgre.**", sqlSessionFactoryRef = "oneSqlSessionFactory")
public class DataSourceConfig1 {
// 將這個對象放入Spring容器中
@Bean(name = "oneDataSource")
// 表示這個數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
@Primary
// 讀取application.properties中的配置參數(shù)映射成為一個對象
// prefix表示參數(shù)的前綴
@ConfigurationProperties(prefix = "spring.datasource.druid.db1")
public DataSource getDateSource1() {
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "oneSqlSessionFactory")
// 表示這個數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
@Primary
// @Qualifier表示查找Spring容器中名字為oneDataSource的對象
public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 設(shè)置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.postgre/*.xml"));
return bean.getObject();
}
@Bean("oneSqlSessionTemplate")
// 表示這個數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
@Primary
public SqlSessionTemplate oneSqlSessionTemplate(
@Qualifier("oneSqlSessionFactory") SqlSessionFactory sessionFactory) {
return new SqlSessionTemplate(sessionFactory);
}
}@Configuration
@MapperScan(basePackages = "com.demo.mapper.mysql", sqlSessionFactoryRef = "twoSqlSessionFactory")
public class DataSourceConfig2 {
// 將這個對象放入Spring容器中
@Bean(name = "twoDataSource")
// 讀取application.properties中的配置參數(shù)映射成為一個對象
// prefix表示參數(shù)的前綴
@ConfigurationProperties(prefix = "spring.datasource.druid.db2")
public DataSource getDateSource1() {
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "twoSqlSessionFactory")
// 表示這個數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
//@Primary
// @Qualifier表示查找Spring容器中名字為oneDataSource的對象
public SqlSessionFactory oneSqlSessionFactory(@Qualifier("twoDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 設(shè)置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.mysql/*.xml"));
return bean.getObject();
}
@Bean("twoSqlSessionTemplate")
// 表示這個數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
//@Primary
public SqlSessionTemplate oneSqlSessionTemplate(
@Qualifier("twoSqlSessionFactory") SqlSessionFactory sessionFactory) {
return new SqlSessionTemplate(sessionFactory);
}
}七、啟動類配置
關(guān)鍵點:去除 exclude = {DataSourceAutoConfiguration.class} 及掃描 com.demo.mapper目錄
@MapperScan("com.demo.mapper")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication .class, args);
}
}八、druid管理頁面
輸入地址 localhost://8081/druid,輸入 admin/admin
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot使用榛子云實現(xiàn)手機短信發(fā)送驗證碼
發(fā)送驗證碼主要用于驗證用戶手機的合法性及敏感操作的身份驗證,本文使用了SpringBoot實現(xiàn),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
java之a(chǎn)ssert關(guān)鍵字用法案例詳解
這篇文章主要介紹了java之a(chǎn)ssert關(guān)鍵字用法案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
Java導(dǎo)入新項目報錯java:JDK?isn‘t?specified?for?module解決辦法
這篇文章主要給大家介紹了關(guān)于Java導(dǎo)入新項目報錯java:JDK?isn‘t?specified?for?module的解決辦法,當(dāng)您在導(dǎo)入Java項目時遇到錯誤時,可以嘗試以下面的方法來處理,需要的朋友可以參考下2024-05-05
Java使用Graphics2D實現(xiàn)字符串文本自動換行
這篇文章主要為大家詳細(xì)介紹了Java如何使用Graphics2D實現(xiàn)字符串文本自動換行,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04
Java微信公眾平臺開發(fā)(3) 接收消息的分類及實體的創(chuàng)建
這篇文章主要為大家詳細(xì)介紹了Java微信公眾平臺開發(fā)第三步,接收消息的分類及實體的創(chuàng)建,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04

