在传统的单体架构中,一个系统对应一个数据库,但在一个分布式系统中,比如微服务,每一个服务对应一个数据库,由于业务的需求,有时需要在一个服务中访问多个数据库的数据,需要配置多数据源,以下是SpringBoot 2.0.5 + MyBatis + .yml 格式配置多数据源的方法。
数据源配置
application.yml 文件的配置
spring:
datasource:
article-service:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: roo
jdbc-url: jdbc:mysql://localhost:3306/articleservice?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true
video-service:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: roo
jdbc-url: jdbc:mysql://localhost:3306/videoservice?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true
# 端口设置
server:
port: 8083
在单数据源的配置中,数据库地址的写法是
url: jdbc:mysql://localhost:3306
多数据源中,需要在 url 前面加上 jdbc-
jdbc-url: jdbc:mysql://localhost:3306
数据源的配置
创建多个配置类,每一个类对应一个数据源的配置,以下是一个数据源的配置。
@Configuration
//配置mbatis接口
@MapperScan(basePackages = "com.hly.springbootmybatis