1. 引入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>8.0.19</scope>
</dependency>
<!--引用多数据源启动器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
2. application.yml 配置文件
primary: dev:默认数据源名称
lazy: false:懒加载,true表示调用数据库才加载,false表示项目启动就加载
spring:
datasource:
dynamic:
primary: dev
lazy: false
datasource:
dev:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.56.128:3396/mybatis_plus?useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: root
dev2:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.56.128:3396/mybatis_plus2?useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: root
3. 结合注解使用
@DS("dev2") :引用数据库dev2,在controller、mapper、service都可以使用!
注:不使用注解,使用默认数据源dev
@RestController
@RequestMapping("user")
@DS("dev2") //引用数据库dev2
@CrossOrigin //解决跨域问题
public class UserController {
@Resource
UserService userService;
@Resource
UserMapper userMapper;
@GetMapping("/{pageNum}/{pageSize}")
public IPage<User> index(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
Page<User> page = userService.page(new Page<User>(pageNum, pageSize));
return page;
}
@GetMapping("/select")
public String select() {
List<User> users = userMapper.selectList(null);
return users.toString();
}
}