SpringBoot多数据源解决方案(转载)
1、开源项目地址:MyBatis Plus & Dynamic Datasource
Maven配置:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.6</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>2.4.2</version> </dependency>
配置文件说明:
server: port: 2080 logging: level: cn.mrxionge.bootdemo: debug org.springframework.web: debug org.springframework.data: debug mybatis-plus: executor-type: simple spring: datasource: #配置hikari连接池 hikari: minimum-idle: 4 maximum-pool-size: 16 connection-timeout: 10000 idle-timeout: 30000 connection-init-sql: set names utf8mb4 #动态数据源配置 dynamic: #主数据源 primary: a01 datasource: #数据源a01 a01: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/a01?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: 123456 #数据源a02 a02: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/a02?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: 123456 #数据源a03 a03: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/a03?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: 123456
测试:新建三个不同的mapper文件,每个mapper文件对应一个数据源,通过调用不同的mapper文件中的方法实现查询不同数据库中的数据
Mapper示例:
@DS(value = "a01") @Mapper public interface MapperA01 extends BaseMapper<UserInfo> { @Select("SELECT * FROM user_info") List<UserInfo> getAllUser(); }
@DS(value = "a02") @Mapper public interface MapperA02 extends BaseMapper<UserInfo> { @Select("SELECT * FROM user_info") List<UserInfo> getAllUser(); }
@DS(value = "a03") @Mapper public interface MapperA03 extends BaseMapper<UserInfo> { @Select("SELECT * FROM user_info") List<UserInfo> getAllUser(); }
Service示例:
@Service public class AppService { @Autowired private MapperA01 mapperA01; @Autowired private MapperA02 mapperA02; @Autowired private MapperA03 mapperA03; /** * 查询A01库中的数据 * * @return 用户信息列表 */ List<UserInfo> getUser01() { return mapperA01.getAllUser(); } /** * 查询A02库中的数据 * * @return 用户信息列表 */ List<UserInfo> getUser02() { return mapperA02.getAllUser(); } /** * 查询A03库中的数据 * * @return 用户信息列表 */ List<UserInfo> getUser03() { return mapperA03.getAllUser(); } }
Controller示例:
@RestController public class AppHandler { @Autowired private AppService service; @GetMapping(path = "/get01") public Mono get01() { //查询A01数据 return Mono.fromSupplier(service::getUser01); } @GetMapping(path = "/get02") public Mono get02() { //查询A02数据 return Mono.fromSupplier(service::getUser02); } @GetMapping(path = "/get03") public Mono get03() { //查询A03数据 return Mono.fromSupplier(service::getUser03); } }
版权声明:本文为CSDN博主「MrXionGe」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31226223/article/details/85322561