1.pom.xml引入相关依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.0.0</version> </dependency>
2.数据源配置
spring: datasource: dynamic: datasource: master: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=GMT%2B8 username: test password: test pg: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://192.168.0.102:3306/testdb?characterEncoding=utf-8&useSSL=false&&serverTimezone=UTC username: test password: test
注意:第一个数据源配置必须为master名称,第二个名称可以任意。
3.使用
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { @DS("master") @Override public Page<User> getUserList(Page<User> page) { return page.setRecords(this.baseMapper.getUserList(page)); } }
通过@DS注解指定数据源操作。
4.其他说明
如果使用了Druid数据库连接池,则需要在启动类增加以下配置@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)