SpringBoot 动态切换数据源
SpringBoot 动态切换数据源
概述:利用上次搭建的MySQL主从复制来实验动态切换数据源。用master来写,用slave用来读。
GITHUB:https://github.com/baomidou/dynamic-datasource-spring-boot-starter
1.搭建一个SpringBoot项目
application.yml
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
url: jdbc:mysql://locahost:33061/zhuantaidb
username: root
password: 123
slave:
url: jdbc:mysql://localhost:33062/zhuantaidb
username: root
password: 123
#......省略
#以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2
StudentService.java
package com.zhuantai.dynamicdata02.service;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.zhuantai.dynamicdata02.mapper.StudentMapper;
import com.zhuantai.dynamicdata02.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author ANTIA1
* @date 2021/7/9 0:03
*/
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
@DS("master") //用来指定数据源
public Integer addStudent(Student student){
return studentMapper.addStudent(student);
}
@DS("slave")
public List<Student> getAllUsers(){
return studentMapper.getAllStudents();
}
}
2.进行测试
package com.zhuantai.dynamicdata02;
import com.zhuantai.dynamicdata02.model.Student;
import com.zhuantai.dynamicdata02.service.StudentService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class DynamicData02ApplicationTests {
@Autowired
StudentService studentService;
@Test
void contextLoads() {
Student student = new Student();
student.setName("张三");
studentService.addStudent(student);
}
@Test
void test01(){
List<Student> allUsers = studentService.getAllUsers();
System.out.println("allUsers = " + allUsers);
}
}