myrpc 学习笔记-009 容错机制

项目地址 欢迎访问

https://gitee.com/longlong5/myrpc

笔记总览 myrpc 学习笔记-001 实现简易版 rpc myrpc 学习笔记-002 配置加载 myrpc 学习笔记-003 Mock 服务代理 myrpc 学习笔记-004 序列化实现和 SPI 机制 myrpc 学习笔记-005 注册中心 myrpc 学习笔记-006 自定义协议 myrpc 学习笔记-007 负载均衡 myrpc 学习笔记-008 重试机制 myrpc 学习笔记-009 容错机制 myrpc 学习笔记-0010 启动机制和注解驱动

架构图v9.0.0

  • 实现容错策略
  • 支持故障恢复 快速失败 故障转移 静默处理
  • 支持自定义容错策略

v9.0.0.png

本模块是 RPC 调用的最后一层安全保障,当重试机制也失败后,由容错策略处理异常,避免整个系统雪崩或直接报错。

模块基于 SPI + 工厂模式 实现,支持 快速失败、故障转移、静默处理、故障恢复 四种策略。

一、模块结构

text
复制代码
fault.tolerant/ ├── TolerantStrategy.java 容错顶层接口 ├── FailFastTolerantStrategy 快速失败 ├── FailSafeTolerantStrategy 静默处理 ├── FailOverTolerantStrategy 故障转移 ├── FailBackTolerantStrategy 故障恢复(降级) ├── TolerantStrategyFactory 工厂 + SPI └── TolerantStrategyKeys 策略常量

二、代码笔记

1. 容错策略接口

统一规范,所有容错策略必须实现 doTolerant

java
复制代码
public interface TolerantStrategy { RpcResponse doTolerant(Map<String, Object> context, Exception e); }

2. 快速失败(默认)FailFast

直接抛出异常,让调用方立即感知,是生产最常用策略。

java
复制代码
public class FailFastTolerantStrategy implements TolerantStrategy { @Override public RpcResponse doTolerant(Map<String, Object> context, Exception e) { throw new RuntimeException("服务报错", e); } }

3. 静默处理 FailSafe

不抛异常,返回空结果,系统继续运行。

java
复制代码
public class FailSafeTolerantStrategy implements TolerantStrategy { @Override public RpcResponse doTolerant(Map<String, Object> context, Exception e) { return new RpcResponse(); } }

4. 故障转移 FailOver

自动切换其他可用节点,提高可用性。

java
复制代码
public class FailOverTolerantStrategy implements TolerantStrategy { @Override public RpcResponse doTolerant(Map<String, Object> context, Exception e) { // 扩展:从服务列表获取下一个节点重试 return null; } }

5. 故障恢复(降级)FailBack

降级调用其他服务或本地方法

java
复制代码
public class FailBackTolerantStrategy implements TolerantStrategy { @Override public RpcResponse doTolerant(Map<String, Object> context, Exception e) { // 扩展:调用降级服务 return null; } }

6. 工厂 + SPI 加载

java
复制代码
public class TolerantStrategyFactory { static { SpiLoader.load(TolerantStrategy.class); } public static TolerantStrategy getTolerantStrategy(String key) { return SpiLoader.getInstance(TolerantStrategy.class, key); } }

7. 策略常量

java
复制代码
public interface TolerantStrategyKeys { String FAIL_BACK = "failBack"; // 降级 String FAIL_FAST = "failFast"; // 快速失败 String FAIL_OVER = "failOver"; // 故障转移 String FAIL_SAFE = "failSafe"; // 静默处理 }

三、调用方式(代理层)

java
复制代码
try { // 重试调用 } catch (Exception e) { // 重试失败,进入容错 TolerantStrategy strategy = TolerantStrategyFactory.getTolerantStrategy("failFast"); RpcResponse response = strategy.doTolerant(context, e); }

四、四种容错策略对比

策略行为优点缺点适用场景
failFast 快速失败立即抛异常简单、快速定位问题可能中断流程核心服务、支付、订单
failSafe 静默处理吞异常,返回空不影响主流程问题难发现日志、监控、非关键统计
failOver 故障转移试下一个节点高可用实现复杂高可用服务集群
failBack 故障恢复降级到其他服务功能不中断需要准备降级逻辑商品详情、首页推荐
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
longlong
下载 APP