SpringBoot feign基于HttpStatus重试

场景

基于springboot开发的项目,对接第三方,第三方的接口有限流策略,某个时间段内有调用频率限制,返回的状态码HttpStatus不是200,而HttpStatus是429。现基于HttpStatus我们发起的重试。

技术点

  1. springboot
  2. feign
    feign要基于HttpStatus重试。

实现

一般我不喜欢配置全局的配置,因为feign的客户端可能会有多个,如果只有一个第三方服务,那可以配置全局的。

  1. 基于HttpStatus为429的解码器
java 复制代码
@Slf4j
public class RemoteErrorDecoder implements ErrorDecoder {
    private static final int TOO_MANY_REQUESTS_CODE = 429;

    private final ErrorDecoder defaultErrorDecoder = new ErrorDecoder.Default();

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() == TOO_MANY_REQUESTS_CODE) {
            log.error("请求因为限流被拒绝,methodKey:{},status:{}", methodKey, response.status());
            return new RetryableException(TOO_MANY_REQUESTS_CODE, "请求因为限流被拒绝", response.request().httpMethod(), null,
                response.request());
        } else {
            log.error("其他状态码,methodKey:{},status:{}", methodKey, response.status());
            return defaultErrorDecoder.decode(methodKey, response);
        }
    }
}
  1. feign配置类
java 复制代码
public class RemoteFeignConfig {
    @Bean
    public ErrorDecoder errorDecoder() {
        return new RemoteErrorDecoder();
    }
		// 重试器可以使用默认的  这边可以根据自己实际情况配置
    @Bean
    public Retryer retryer() {
        return new Retryer.Default(30000, 30000, 3);
    }
}
  1. feign client
java 复制代码
@FeignClient(name = "xxx", url = "xxx", configuration = RemoteFeignConfig.class)
public interface RemoteService {
  // TODO 调用的接口
}
相关推荐
2601_963870212 分钟前
【计算机毕业设计】基于Spring boot+Vue系统的健身俱乐部管理系统的设计与实现
spring boot·后端·课程设计
andongni20311 分钟前
Spring Boot基础应用开发与部署
java·spring boot·后端
lupai16 分钟前
增值税发票 OCR 识别 API 新手接入指南
java·前端·ocr
TELL52117 分钟前
Sonar质量门禁
java
java修仙传21 分钟前
从网页禅道到 AI 能调用的工具:我的禅道 MCP 实现思路分享
java·人工智能·python·ai应用·mcp开发
HAYDENR21 分钟前
依赖数据迁移工具做增量同步有哪些易错点?调整数据迁移工具策略怎么保证断点续传可靠?
java·大数据·数据库
IT利刃出鞘33 分钟前
SpringBoot--解决@Valid放在接口的List上时无效的问题
java·spring
mqiqe37 分钟前
AgentScope Java Harness:2. 上下文压缩:让长期 Agent 永不“失忆“
java·开发语言
梦想的旅途241 分钟前
企业微信API实战:Python自动化消息推送
java·前端·python·自动化·企业微信
YOU OU41 分钟前
RabbitMQ运维
java·rabbitmq·java-rabbitmq