多数据源配置
先整合mysql和mybatis-plus
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
注意:一定要指定版本或者进行版本管理否则会影响yml和启动报错,因为不涉及具体的mybatis连接驱动访问数据库,就没有配置mapper和扫描路径之类的
datasource:
url: jdbc:mysql://139.198.105.30:3306/edu
username: root
password: 123abcABC!@#
driver-class-name: com.mysql.cj.jdbc.Driver
导入mybatisplus和mysql驱动后 测试启动一下如果成功则进行下面的步骤
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${version}</version>
</dependency>
配置多数据源
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://139.198.105.30:3306/edu
username: root
password: 123abcABC!@#
driver-class-name: com.mysql.cj.jdbc.Driver
slave_1:
url: jdbc:mysql://139.198.105.30:3306/edu2
username: root
password: 123abcABC!@#
driver-class-name: com.mysql.cj.jdbc.Driver
@MapperScan(basePackages = "com.example.seatea.mapper")
@EnableDiscoveryClient
@SpringBootApplication
public class SeateaApplication {
@Service
public class userserviceImpl extends ServiceImpl<userMapper,user> implements userservice {
@DS("slave_1") //核心注解 使用哪个数据源 未使用的默认数据源
@Override
public void selectBYMaster() {
user byId = this.getById(1);
System.out.println("slave_1");
System.out.println(byId.getUserName());
}
@Override
public void selectBySlave() {
user byId = this.getById(1);
System.out.println("默认");
System.out.println(byId.getUserName());
}
}
概括: 核心就是导入多数据源的依赖,导入mybatis和mysql的驱动,配置文件配置多数据源的信息,在生成mapper和一系列模块代码后,不打多数据源注解的走默认数据源,打@DS注解的走从数据源