MyBatis-Plus实现多数据源的示例代码

2025-05-29 0 103

多数据源的目的在于一个代码模块可调用多个数据库的数据进行某些业务操作。

MyBatis-Plus开发者写了一个多数据源叫dynamic-datasource-spring-boot-starter,非常简单易用。

dynamic-datasource-spring-boot-starter文档

官方文档部分截图:

MyBatis-Plus实现多数据源的示例代码

第三方集成的,基本上是目前比较主流的(用的比较多)。

一、添加maven依赖

?

1

2

3

4

5
<dependency>

<groupid>com.baomidou</groupid>

<artifactid>dynamic-datasource-spring-boot-starter</artifactid>

<version>2.5.4</version>

</dependency>

二、配置文件修改(application.yml)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43
spring:

datasource:

dynamic:

primary: db1 #设置默认的数据源,默认值为master

datasource:

db1: #数据源db1

driver-class-name: com.mysql.jdbc.driver

url: jdbc:mysql://127.0.0.1:3306/wordpress_master?useunicode=true&characterencoding=utf-8&servertimezone=asia/shanghai

username: root

password: 123456

db2: #数据源db2

driver-class-name: com.mysql.jdbc.driver

url: jdbc:mysql://127.0.0.1:3306/wordpress_slave?useunicode=true&characterencoding=utf-8&servertimezone=asia/shanghai

username: root

password: 123456

type: com.alibaba.druid.pool.druiddatasource

druid:

initial-size: 10

max-active: 100

min-idle: 10

max-wait: 60000

pool-prepared-statements: true

max-pool-prepared-statement-per-connection-size: 20

time-between-eviction-runs-millis: 60000

min-evictable-idle-time-millis: 300000

#oracle需要打开注释

#validation-query: select 1 from dual

test-while-idle: true

test-on-borrow: false

test-on-return: false

stat-view-servlet:

enabled: true

url-pattern: /druid/*

#login-username: admin

#login-password: admin

filter:

stat:

log-slow-sql: true

slow-sql-millis: 1000

merge-sql: false

wall:

config:

multi-statement-allow: true

三、完成成1、2步后,启动应用

如果控制台不报错且出现如下图所示,就表示成功整合:

MyBatis-Plus实现多数据源的示例代码

四、注意事项

启动主类需要排除druid相关依赖,否则会出现如下错误:

***************************
application failed to start
***************************

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

解决办法,加上如下代码即可:

?

1
@springbootapplication(exclude = druiddatasourceautoconfigure.class)

到此这篇关于mybatisplus实现多数据源的示例代码的文章就介绍到这了,更多相关mybatis-plus 多数据源内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://segmentfault.com/a/1190000038171792

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 MyBatis-Plus实现多数据源的示例代码 https://www.kuaiidc.com/104074.html

相关文章

发表评论
暂无评论