文章目录
- 一、pom依赖
- 二、application.yml多数据源配置
- 三、持久层
- 3.1. UserMapper 接口
- 3.2. 接口映射UserMapper.xml(可以不写)
- 四、逻辑处理层
- 4.1. IUserService 接口
- 4.2. 接口实现类IUserServiceImpl
- 五、通用返回对象封装
- 六、测试UserController
- 七、启动类加扫描mapper注解
- 八、数据库脚本
- 8.1. masterdb.sql
- 8.2. slavedb.sql
- 九、测试验证
- 9.1. 主库新增用户
- 9.2. 从库新增用户
- 9.3. 获取主库用户列表
- 9.4. 获取从库用户列表
- 9.5.
一、pom依赖
需要引入与SpringBoot整合好的动态数据源依赖,以及mybatis-plus相关依赖包
<!--SpringBoot mvc启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 多数据源依赖 --><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>${dynamic-datasource.version}</version></dependency><!--lombok 简化java代码--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version></dependency><!-- Spring Boot Mybatis plus 依赖 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version></dependency><!--Mysql数据库驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version><scope>runtime</scope></dependency><!--单元测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
二、application.yml多数据源配置
直接复制到你的项目中即可,通过primary来指定默认数据源,配置如下:
server:port: 80# 数据源配置
spring:datasource:dynamic:primary: master #设置默认的数据源datasource:master:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Driver# 从数据源配置slave:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Drivermp-enabled: true# 数据源加载日志
logging:level:com.xkcoding.multi.datasource.mybatis: debug
三、持久层
3.1. UserMapper 接口
public interface UserMapper extends BaseMapper<User> {
}
3.2. 接口映射UserMapper.xml(可以不写)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gblfy.springboot.mybatisplus.entity.User">
</mapper>
四、逻辑处理层
4.1. IUserService 接口
import com.baomidou.mybatisplus.extension.service.IService;
import com.gblfy.springboot.mybatisplus.entity.User;import java.util.List;public interface IUserService extends IService<User> {/*** 往从库中插入数据** @param user*/Integer addUserToSlave(User user);/*** 主库插入** @param user*/Integer addUserToMaster(User user);/*** 获取主库用户列表** @return*/List<User> findMasterUserList();/*** 获取从库用户列表** @return*/List<User> findSlaveUserList();
}
4.2. 接口实现类IUserServiceImpl
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gblfy.springboot.mybatisplus.entity.User;
import com.gblfy.springboot.mybatisplus.mapper.UserMapper;
import com.gblfy.springboot.mybatisplus.service.IUserService;
import org.springframework.stereotype.Service;import java.util.List;/*** @author gblfy* @ClassNme IUserServiceImpl* @Description TODO* @Date 2019/12/8 10:21* @version1.0*/
@Service
@DS("master")
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {@DS("slave")@Overridepublic Integer addUserToSlave(User user) {return null;}@Overridepublic Integer addUserToMaster(User user) {return null;}@Overridepublic List<User> findMasterUserList() {return null;}@DS("slave")@Overridepublic List<User> findSlaveUserList() {return null;}
}
五、通用返回对象封装
/*** 公共返回实体类*/
@Data
public class ResultObject {/*** 可为数组或字符串等,可记录错误信息或正常返回的相关信息*/private Object message;/*** 返回码 200代表正常 1代表失败*/private int code;private Object result;}
六、测试UserController
import com.gblfy.springboot.mybatisplus.entity.User;
import com.gblfy.springboot.mybatisplus.service.IUserService;
import com.gblfy.springboot.mybatisplus.utils.ResultObject;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author: gblfy* @desc: 用户控制层* @date: 2019/12/8 10:25*/
@RestController
@RequestMapping("/user")
@Data
public class UserController {@Autowiredprivate IUserService userService;/*** 主库新增用户* @param user* @return*/@GetMapping("addUserToMaster")public Object addUserToMaster(User user){ResultObject resultObject = new ResultObject();try {User userMaster = User.builder().name(user.getName()).age(user.getAge()).email(user.getEmail()).build();resultObject.setResult(userService.addUserToMaster(userMaster));resultObject.setCode(200);resultObject.setMessage("主库新增用户成功");} catch (Exception e) {resultObject.setCode(-1);resultObject.setMessage("主库新增用户失败");e.printStackTrace();}return resultObject;}/*** 从库新增用户* @param user* @return*/@GetMapping("addUserToSlave")public Object addUserToSlave(User user){ResultObject resultObject = new ResultObject();try {User userSlave = User.builder().name(user.getName()).age(user.getAge()).email(user.getEmail()).build();resultObject.setResult(userService.addUserToSlave(userSlave));resultObject.setCode(200);resultObject.setMessage("从库新增用户成功");} catch (Exception e) {resultObject.setCode(-1);resultObject.setMessage("从库新增用户失败");e.printStackTrace();}return resultObject;}/*** 获取主库用户列表* @return*/@RequestMapping("findMasterUserList")public Object findMasterUserList(){ResultObject resultObject = new ResultObject();try {resultObject.setResult(userService.findMasterUserList());resultObject.setCode(200);resultObject.setMessage("获取主库用户列表成功");} catch (Exception e) {resultObject.setCode(-1);resultObject.setMessage("获取主库用户列表失败");e.printStackTrace();}return resultObject;}/*** 获取从库用户列表* @return*/@RequestMapping("findSlaveUserList")public Object findSlaveUserList(){ResultObject resultObject = new ResultObject();try {resultObject.setResult(userService.findSlaveUserList());resultObject.setCode(200);resultObject.setMessage("获取从库用户列表成功");} catch (Exception e) {resultObject.setCode(-1);resultObject.setMessage("获取从库用户列表失败");e.printStackTrace();}return resultObject;}
}
七、启动类加扫描mapper注解
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan(basePackages = "com.gblfy.springboot.mybatisplus.mapper")
public class SpringbootApplication {public static void main(String[] args) {SpringApplication.run(SpringbootApplication.class, args);}
}
八、数据库脚本
8.1. masterdb.sql
DROP TABLE IF EXISTS user;CREATE TABLE user
(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年龄',email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',create_time DATETIME DEFAULT NULL COMMENT '创建时间',PRIMARY KEY (id)
);DELETE FROM user;INSERT INTO user (id, name, age, email, create_time) VALUES
(1, 'Jone', 18, 'test1@gblfy.com','2019-01-11 14:20:20'),
(2, 'Jack', 20, 'test2@gblfy.com','2019-02-05 11:12:22'),
(3, 'Tom', 28, 'test3@gblfy.com','2019-02-14 08:31:16'),
(4, 'Sandy', 21, 'test4@gblfy.com','2019-01-14 09:15:15'),
(5, 'Billie', 24, 'test5@gblfy.com','2019-01-14 09:48:16');
8.2. slavedb.sql
DROP TABLE IF EXISTS user;CREATE TABLE user
(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年龄',email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',create_time DATETIME DEFAULT NULL COMMENT '创建时间',PRIMARY KEY (id)
);DELETE FROM user;INSERT INTO user (id, name, age, email, create_time) VALUES
(1, 'Jone2', 18, 'test1@gblfy.com','2019-01-11 14:20:20'),
(2, 'Jack2', 20, 'test2@gblfy.com','2019-02-05 11:12:22'),
(3, 'Tom2', 28, 'test3@gblfy.com','2019-02-14 08:31:16'),
(4, 'Sandy2', 21, 'test4@gblfy.com','2019-01-14 09:15:15'),
(5, 'Billie2', 24, 'test5@gblfy.com','2019-01-14 09:48:16');
九、测试验证
9.1. 主库新增用户
http://localhost/user/addUserToMaster?name=gblfy&age=66&email=gbly02@gmail.com
9.2. 从库新增用户
http://localhost/user/addUserToSlave?name=gblfy02&age=66&email=gbly02@gmail.com
9.3. 获取主库用户列表
http://localhost/user/findMasterUserList
9.4. 获取从库用户列表
http://localhost/user/findSlaveUserList
9.5.
http://localhost/user/addUserToMaster?name=gblfy&age=66&email=gbly02@gmail.com