开发经验总结: 读写分离简单实现

news/2024/9/28 21:26:37/

背景

file

使用mysql的代理中间件,某些接口如果主从同步延迟大,容易出现逻辑问题。所以程序中没有直接使用这个中间件。

依赖程序逻辑,如果有一些接口可以走读库,需要一个可以显示指定读库的方式来连接读库,降低主库的压力。

所以需要一个能配置多个数据源,通过注解或者代码方式设置读还是写数据源的方法。

实现方式

使用MybatisPlus的多数据源切换的能力。

github地址: https://github.com/baomidou/dynamic-datasource

已经封装好了。直接使用就行。

介绍

dynamic-datasource-spring-boot-starter 是一个基于springboot的快速集成多数据源的启动器。

其支持 Jdk 1.7+, SpringBoot 1.5.x 2.x.x 3.x.x。 JPA用户不建议使用,JPA自带事务,无法连续切库。

特性:

  • 支持 数据源分组 ,适用于多种场景 纯粹多库 读写分离 一主多从 混合模式。
  • 支持数据库敏感配置信息 加密(可自定义) ENC()。
  • 支持每个数据库独立初始化表结构schema和数据库database。
  • 支持无数据源启动,支持懒加载数据源(需要的时候再创建连接)。
  • 支持 自定义注解 ,需继承DS(3.2.0+)。
  • 提供并简化对Druid,HikariCp,BeeCp,Dbcp2的快速集成。
  • 提供对Mybatis-Plus,Quartz,ShardingJdbc,P6sy,Jndi等组件的集成方案。
  • 提供 自定义数据源来源 方案(如全从数据库加载)。
  • 提供项目启动后 动态增加移除数据源 方案。
  • 提供Mybatis环境下的 纯读写分离 方案。
  • 提供使用 spel动态参数 解析数据源方案。内置spel,session,header,支持自定义。
  • 支持 多层数据源嵌套切换 。(ServiceA >>> ServiceB >>> ServiceC)。
  • 提供 基于seata的分布式事务方案
  • 提供 本地多数据源事务方案。

我们需要的是纯读写分离 方案,它已经内置了。

功能范围:

  1. 本框架只做 切换数据源 这件核心的事情,并不限制你的具体操作,切换了数据源可以做任何CRUD。
  2. 配置文件所有以下划线 分割的数据源 首部 即为组的名称,相同组名称的数据源会放在一个组下。
  3. 切换数据源可以是组名,也可以是具体数据源名称。组名则切换时采用负载均衡算法切换。
  4. 默认的数据源名称为 master ,你可以通过 spring.datasource.dynamic.primary 修改。
  5. 方法上的注解优先于类上注解。
  6. DS支持继承抽象类上的DS,暂不支持继承接口上的DS。

使用步骤

1.引入依赖。

<dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>${version}</version>
</dependency>

2.配置数据源

spring:datasource:dynamic:primary: master #设置默认的数据源或者数据源组,默认值即为masterstrict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源datasource:master:url: jdbc:mysql://xx.xx.xx.xx:3306/dynamicusername: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置slave_1:url: jdbc:mysql://xx.xx.xx.xx:3307/dynamicusername: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driverslave_2:url: ENC(xxxxx) # 内置加密,使用请查看详细文档username: ENC(xxxxx)password: ENC(xxxxx)driver-class-name: com.mysql.jdbc.Driver#......省略#以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2

3.使用注解切换数据源。

@DS 可以注解在方法上或类上,同时存在就近原则 方法上注解 优先于 类上注解

file

@Service
@DS("slave")
public class UserServiceImpl implements UserService {@Autowiredprivate JdbcTemplate jdbcTemplate;public List selectAll() {return  jdbcTemplate.queryForList("select * from user");}@Override@DS("slave_1")public List selectByCondition() {return  jdbcTemplate.queryForList("select * from user where age >10");}
}

业务集成

我们的程序使用的经典的三层结构,即MVC .

画板

看到我们的框架是已经集成了dynamicSource的。如果没有,则加一下依赖即可。

以crm服务为例子。写了一些测试代码,进行验证测试。

package com.pig4cloud.pigx.crm.controller;import com.baomidou.dynamic.datasource.annotation.DS;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import com.pig4cloud.pigx.crm.mapper.AiAgentMapper;
import com.pig4cloud.pigx.crm.service.AiAgentService;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;@RestController
@RequiredArgsConstructor
@Tag(description = "test read write", name = "测试读写分离")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Valid
@Slf4j
public class TestDsController {private final AiAgentMapper aiAgentMapper;private final AiAgentService aiAgentService;@GetMapping("/testD")@ResponseBody//@Inner(value = false)public R testD() {return R.ok(aiAgentMapper.selectList(null));}@GetMapping("/testRead")@ResponseBody//@Inner(value = false)@DS("read")public R testRead() {return R.ok(aiAgentMapper.selectList(null));}@GetMapping("/testMaster")@ResponseBody//@Inner(value = false)@DS("master")public R testMaster() {return R.ok(aiAgentMapper.selectList(null));}@GetMapping("/testHe")@ResponseBody//@Inner(value = false)@DS("master")public R testHe() {return R.ok(aiAgentService.listTest());}@GetMapping("/testHe2")@ResponseBody//@Inner(value = false)@DS("read")public R testHe2() {return R.ok(aiAgentService.listTest2());}@GetMapping(value = "/testHe3",produces = "application/json")@ResponseBody//@Inner(value = false)public R testHe3() {Map<String, Object> dataMap = new HashMap<>();dataMap.put("read", aiAgentService.listTest());dataMap.put("master", aiAgentService.listTest2());return R.ok(dataMap);}}

对应的Service实现代码:

@Service
@Slf4j
@RequiredArgsConstructor
public class AiAgentServiceImpl extends ServiceImpl<AiAgentMapper, AiAgentEntity> implements AiAgentService {@Override@DS("read")public List<AiAgentEntity> listTest() {return baseMapper.selectList(null);}@Override@DS("master")public List<AiAgentEntity> listTest2() {return baseMapper.selectList(null);}
}

测试用例和结果:

测试接口和场景测试说明预期结果测试结果
/testD不加任何注解走主库- [x] 走主库 ![]file
/testRead添加了读库注解走读库- [x] 走读库file
/testMaster添加了主库注解走主库- [x] 走主库file
/testHe上层加主库注解,下层加读库注解走读库- [x] 走读库file
/testHe2上层加读库注解,下层加写库注解走主库- [x] 走主库 file
/testHe3在中层的方法分别加读库和写库注解分别走读库和主库- [x] 分别走读库和读库file

目前需要增加读写分离的服务。

服务增加读写分离的原因是否完成增加
crm后台列表查询页面, openAPI的读接口,直接走读库;- [x]
email后台列表查询页面, openAPI的读接口,直接走读库;- [ ]
phone后台列表查询页面, openAPI的读接口,直接走读库;- [ ]
ssm后台列表查询页面, openAPI的读接口,直接走读库;- [ ]
upms后台列表查询页面, openAPI的读接口,直接走读库;- [ ]

源码研究

3.6.0版本。基于这个进行分析。

1 自动装配类

file

配置属性:DynamicDataSourceProperties

属性说明
primary默认的库
strict严格检查
p6spy日志输出
seata是否开启seata
lazy是否懒加载数据源
setaModeAT模式
publicKey加密key
datasource数据源,可以单独配置;
strategy负载均衡策略
druid数据源
hikari数据源
beecp数据源
dbcp2数据源
aopaop配置,有默认值

DataSourceProperty

属性说明说明
poolName连接池名称
type连接类型
driverClassName驱动名称
url连接url
username用户名
password密码
jndiNamejndi中的名称
init初始化配置
p6spy日志输出
seata是否开启seata
lazy是否懒加载数据源
publicKey加密key
druid数据源
hikari数据源
beecp数据源
dbcp2数据源

DatasourceInitProperties

属性名说明
schema建表脚本
data数据脚本
continueOnError错误是否继续
separator分隔符

2 自动装配逻辑

file

基于切面实现。

小结

集成使用了mybatisPlus自带的多数据源实现了读写分离,并探究了源码实现过程。

详细过程可以看我的视频号。

原创不易,关注诚可贵,转发价更高!转载请注明出处,让我们互通有无,共同进步,欢迎沟通交流。


http://www.ppmy.cn/news/1530650.html

相关文章

【C++】继承(下)

个人主页~ 继承&#xff08;上&#xff09;~ 继承 四、派生类的默认成员函数五、继承与友元六、继承与静态成员七、复杂的菱形继承以及菱形虚拟继承1、菱形继承2、菱形虚拟继承 八、继承的总结与反思继承和组合 四、派生类的默认成员函数 派生类的构造函数必须调用基类的构造…

SpringBoot开发——整合P6Spy详细记录SQL执行耗时情况

文章目录 1、p6spy是什么2、SpringBoot整合P6Spy2.1 引入依赖2.2 数据库操作2.3 测试代码2.4 p6spy配置2.5 其它自定义监控并优化数据库操作的性能至关重要。为了提升应用性能和数据库效率,很多项目会实现一个功能来打印SQL执行耗时。这一功能通过在SQL查询执行前后记录时间戳…

SourceTree保姆级教程1:(克隆,提交,推送)

本人认为sourceTree 是最好用的版本管理工具&#xff0c;下面将讲解下sourceTree 客户端工具 克隆&#xff0c;提交&#xff0c;推送 具体使用过程&#xff0c;废话不多说直接上图。 使用步骤&#xff1a; 首先必须要先安装Git和sourceTree&#xff0c;如何按照参考其它文章&…

MT76X8、MT7621、MT7981和QCA9531的GPIO列表

一、 MT76X8 GPIO列表; 二、 MT7621 GPIO列表; 三、MTK7981 GPIO列表; 四、QCA9531 GPIO列表;

2024.09.22 leetcode 每日一题

Excel表列名称 给你一个整数 columnNumber &#xff0c;返回它在 Excel 表中相对应的列名称。 https://leetcode.cn/problems/excel-sheet-column-title/description/ 我的解法&#xff1a; class Solution { public:string convertToTitle(int columnNumber) {std::map<…

解释python requests包的timeout

解释python requests包的timeout 哈哈哈。。。。垃圾python又来了 1 问题 你能看懂下面两个timeout的含义就不用看下面的内容了。 requests.get(http://example.com, timeout(2, 5)) requests.get(http://127.0.0.1:5000/api,timeout1)官网解释&#xff01;&#xff01;&am…

【学术会议征稿】第四届人工智能、机器人和通信国际会议(ICAIRC 2024)

第四届人工智能、机器人和通信国际会议&#xff08;ICAIRC 2024&#xff09; 2024 4th International Conference on Artificial Intelligence, Robotics, and Communication 第四届人工智能、机器人和通信国际会议&#xff08;ICAIRC 2024&#xff09;定于2024年12月27-29日…

2025考研倒计时 考研时间公布了 你准备好复习冲刺了吗?

2025考研倒计时 考研时间公布了 你准备好复习冲刺了吗&#xff1f;今年的考研时间终于公布了&#xff1a; 正式报名时间2024.10.15-2024.10.28&#xff0c;初试时间12月21日&#xff0c;相信很多学子们已经做好冲刺的准备了。 在这关键的90天的时间内&#xff0c;如何做到时刻…