springboot多数据源,springboot 自动添加数据

首页 > 机动车 > 作者:YD1662023-11-09 18:44:46

通过springboot druid mybatisplus使用注解整合第一步:引入相关的依赖jar,如下:

<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就是你的数据源的名字,可以随便定义 }第五步:到此,结束,谢谢!

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.