当前位置: 首页 > 图灵资讯 > 技术篇> SpringBoot下动态数据源

SpringBoot下动态数据源

来源:图灵教育
时间:2023-05-23 09:29:50

 1.引入依赖

复制xml代码<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-jdbc</artifactId></dependency>
2.配置数据源

application.properties数据源信息配置在文件中:

properties复制代码代码# Spring.datasource.url=jdbc:mysql://localhost:3306/main_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# Spring从数据源配置.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/master_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.dynamic.datasource.master.username=rootspring.dynamic.datasource.master.password=rootspring.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driverspring.dynamic.datasource.slave.url=jdbc:mysql://localhost:3306/slave_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.dynamic.datasource.slave.username=rootspring.dynamic
properties复制代码代码# Spring.datasource.url=jdbc:mysql://localhost:3306/main_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# Spring从数据源配置.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/master_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.dynamic.datasource.master.username=rootspring.dynamic.datasource.master.password=rootspring.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driverspring.dynamic.datasource.slave.url=jdbc:mysql://localhost:3306/slave_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.dynamic.datasource.slave.username=rootspring.dynamic