<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
# mybatis-plus
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
# 配置动态数据源
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.8</version>
</dependency>
# 阿里的数据库连接池
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
# mysql
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
# lombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
第二步:jdbc配置文件,如下:
#默认数据源
spring.datasource.dynamic.primary = master
#数据源一
spring.datasource.dynamic.datasource.master.username = root
spring.datasource.dynamic.datasource.master.password = root123456
spring.datasource.dynamic.datasource.master.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.master.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
#数据源二
spring.datasource.dynamic.datasource.slave.username = root
spring.datasource.dynamic.datasource.slave.password = root
spring.datasource.dynamic.datasource.slave.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.slave.url = jdbc:mysql://172.18.20.23:3306/task?useUnicode=true&characterEncoding=UTF-8
第三步:项目启动类排除(DruidDataSourceAutoConfigure):
//DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找 url, username, password 等。动态数据源 URL 等配置是在 dynamic 下,因此需要排除,否则会报错。在项目启动类排除:
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第四步:给使用非默认数据源添加注解@DS,如下:
@Service
@DS("slave")
public class CompanyThirdDataServiceImpl extends ServiceImpl<CompanyThirdDataMapper, CompanyThirdData> implements CompanyThirdDataService {
//@DS("slave") slave就是你的数据源的名字,可以随便定义
}
第五步:到此,结束,谢谢!