springboot实现多数据源读取
1 环境准备
数据库准备,提前准备好两个库,里面都用一张user表,只包含两个字段name和age。
demo1库里面有两条数据

demo2库里面也有两条数据,值与demo1的user表不同做区分。

2 利用dynamic-datasource实现
可以参考https://github.com/baomidou/dynamic-datasource-spring-boot-starter
1 2 3 4 5 6
| <!-- dynamic-datasource --> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.6.0</version> </dependency>
|
配置文件修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| spring: datasource: dynamic: primary: db1 strict: false datasource: db1: url: jdbc:mysql://localhost:3306/demo1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useAffectedRows=true&rewriteBatchedStatements=true username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver db2: url: jdbc:mysql://localhost:3306/demo2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useAffectedRows=true&rewriteBatchedStatements=true username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver
mybatis: type-aliases-package: com.chenghao.train.model.entity mapper-locations: classpath:mapper/*.xml
|
代码
UserController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @RestController @RequestMapping("user") public class UserController {
@Resource private IUserService userService;
@GetMapping("v1") @ResponseBody public List<UserEntity> list() { return userService.selectAll(); }
@GetMapping("v2") @ResponseBody public List<UserEntity> list2() { return userService.selectAll2(); } }
|
UserServiceImpl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Service public class UserServiceImpl implements IUserService {
@Resource private UserMapper userMapper; @Override @DS("db1") public List<UserEntity> selectAll() { return userMapper.selectAll(); }
@Override @DS("db2") public List<UserEntity> selectAll2() { return userMapper.selectAll(); } }
|
3 测试
运行main方法,进行测试观察结果

