好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

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

dynamic-datasource-spring-boot-starter文档

官方文档部分截图:

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

一、添加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步后,启动应用

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

四、注意事项

启动主类需要排除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 )

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

原文链接:https://segmentfault测试数据/a/1190000038171792

查看更多关于MyBatis-Plus实现多数据源的示例代码的详细内容...

  阅读:25次