myrpc 学习笔记-008 重试机制

项目地址 欢迎访问

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 启动机制和注解驱动

架构图v8.0.0

  • 实现重试策略
  • 支持不重试 固定时间间隔 重试策略
  • 支持自定义重试策略

v8.0.0.png

这是 RPC 框架的重试机制的具体实现,负责在调用失败时自动重试,提升调用成功率,基于 Guava Retrying 实现,支持 不重试 / 固定间隔重试 两种策略,可扩展、可配置、SPI 加载。

一、模块结构

text
复制代码
fault.retry/ ├── RetryStrategy.java 重试策略接口 ├── NoRetryStrategy.java 不重试策略 ├── FixedIntervalRetryStrategy.java 固定时间间隔重试 ├── RetryStrategyFactory.java 重试策略工厂(SPI) └── RetryStrategyKeys.java 策略常量

二、代码笔记

1. 重试策略接口

统一规范,所有重试策略都必须实现 doRetry 方法。

java
复制代码
public interface RetryStrategy { RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception; }

2. 不重试策略

直接执行一次,失败立即抛出异常。

java
复制代码
public class NoRetryStrategy implements RetryStrategy { @Override public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception { return callable.call(); } }

3. 固定间隔重试策略

基于 Guava Retrying 实现,功能强大。

重试规则:

  • 出现 Exception 就重试
  • 每次间隔 3秒
  • 最多 3次尝试(1次正常+2次重试)
  • 每次重试打印日志
java
复制代码
public class FixedIntervalRetryStrategy implements RetryStrategy { @Override public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception { Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder() .retryIfExceptionOfType(Exception.class) // 异常重试 .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)) // 等待3秒 .withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 最多试3次 .withRetryListener(attempt -> { log.info("重试次数 {}", attempt.getAttemptNumber()); }) .build(); return retryer.call(callable); } }

4. 重试策略工厂 + SPI

支持 SPI 动态加载,可无缝扩展更多重试策略。

java
复制代码
public class RetryStrategyFactory { static { SpiLoader.load(RetryStrategy.class); } private static final RetryStrategy DEFAULT = new NoRetryStrategy(); public static RetryStrategy getRetryStrategy(String key) { return SpiLoader.getInstance(RetryStrategy.class, key); } }

5. 策略常量

java
复制代码
public interface RetryStrategyKeys { String NO = "no"; // 不重试 String FIXED_INTERVAL = "fixedInterval"; // 固定间隔 }

三、使用方式(代理层调用)

java
复制代码
RetryStrategy retryStrategy = RetryStrategyFactory.getRetryStrategy("fixedInterval"); RpcResponse response = retryStrategy.doRetry(() -> VertxTcpClient.doRequest(rpcRequest, serviceMetaInfo) );

四、重试策略对比

策略行为优点缺点适用场景
no(不重试)一次失败立即抛错最快、无延迟不稳定实时性高、非幂等接口
fixedInterval(固定间隔)失败等3秒再试,最多3次提高成功率、稳定增加调用耗时网络波动、幂等接口
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
longlong
下载 APP