依赖
<!-- 动态数据源 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.5.0</version> </dependency>
yml
spring: datasource: dynamic: primary: mater #设置默认的数据源或者数据源组,默认值即mater strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常, false使用默认数据源 datasource: mater: driver-class-name: com.mysql.cj.jdbc.Driver # url: jdbc:mysql://120.79.193.94:3306/dashanvip?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 url: jdbc:mysql://39.108.223tf-8&useSSL=false&serverTimezone=GMT%2B8 username: root password: # 多数据源配置 multi-datasource: url: jdbc:mysql://120.ng?characterEncoding=UTF-8&useUnicode=true&useSSL=false username: root password: driver-class-name: com.mysql.jdbc.Driver
使用的方法
@DS("")
@Mapper @DS("multi-datasource") public interface AppTeacherMapper extends BaseMapper<AppTeacher> { }
DynamicDataSourceContextHolder.push("multi-datasource"); //替换数据源