1、添加所用到的依赖pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mybatis-plus的依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.1</version> </dependency> <!-- mybatis-plus的自动生成依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.0.6</version> </dependency> <!-- mybatis-plus多数据源 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.1</version> </dependency>
2、配置application.yml配置文件
spring: datasource: dynamic: primary: master #设置默认的数据源或者数据源组,默认值即为master strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源 datasource: master: url: jdbc:mysql://8.129.215.115:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver slave_1: url: jdbc:mysql://8.129.215.115:3306/my_test?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver slave_2: url: jdbc:mysql://8.129.215.115:3306/cache?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
3、编写TestService 进行测试
@Service public class TestService { @Autowired private JdbcTemplate jdbcTemplate; @DS("master") public List selectAll() { return jdbcTemplate.queryForList("select * from my_user"); } @DS("slave_1") public List test01() { return jdbcTemplate.queryForList("select * from tb_user"); } @DS("slave_2") public List selectByCondition() { return jdbcTemplate.queryForList("select * from employee"); } }
3、编写测试类进行测试
@Autowired private TestService testService; @Test void contextLoads() { List list = testService.selectAll(); System.out.println(list); List list1 = testService.test01(); System.out.println(list1); List list2 = testService.selectByCondition(); System.out.println(list2); }