1、引入需要的pom依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
2、写配置文件
server:
port: 18081
servlet:
context-path: /api
max-http-header-size: 102400
spring:
jwt:
secret: swedrfhjkrd5tyuhjregh
application:
name: project
datasource:
dynamic:
primary: db1
datasource:
db1:
username: test
password: test123
url: jdbc:mysql://xxxx:29330/test1?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
db2:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
durid:
initial-size: 1
max-active: 20
min-idle: 1
max-wait: 60000
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
3.默认是主数据库,需要使用别的数据库只需要使用@DS注解然后加上配置yml文件的数据库就行了(如:db2)
@DS("db2")
List<User> queryTest();