服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - MyBatis-Plus实现多数据源的示例代码

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

2021-09-24 00:44youcongtech Java教程

这篇文章主要介绍了MyBatis-Plus实现多数据源的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

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)

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

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

延伸 · 阅读

精彩推荐