<!-- https://mvnrepository.com/artifact/com.baomidou/dynamic-datasource-spring-boot-starter --><dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.0.0</version></dependency>
全局配置文件,配置三个数据源,分别起名为master,slave_1,slave_2:
spring: datasource: dynamic: primary: master #设置默认的数据源或者数据源组,默认值即为master datasource: master: username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot?serverTimezone=Asia/Shanghai slave_1: username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot2?serverTimezone=Asia/Shanghai slave_2: username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot3?serverTimezone=Asia/Shanghai
还要新建三个数据库,为了简单就随便意思一下吧,分别起名为springboot,springboot2,springboot3。然后在每个数据库里面都新建上一张名为person的表,并存入不同的数据。测试的时候就来查这些个person的列表。
package com.ge.controller;import com.baomidou.dynamic.datasource.annotation.DS;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;import java.util.Map;@Controllerpublic class MyController { @Autowired JdbcTemplate jdbcTemplate; @GetMapping("find") @ResponseBody public List<Map<String, Object>> find(){ List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from person"); return list; } @DS(value = "slave_1") @GetMapping("find1") @ResponseBody public List<Map<String, Object>> find1(){ List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from person"); return list; } @DS(value = "slave_2") @GetMapping("find2") @ResponseBody public List<Map<String, Object>> find2(){ List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from person"); return list; }}
运行项目,分别请求不同数据源所对应的接口,下面看请求结果:
请求接口http://localhost:8080/find:
联系客服