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 调用的接口
}
相关推荐
程序员三明治38 分钟前
选 Redis Stream 还是传统 MQ?队列选型全攻略(适用场景、优缺点与实践建议)
java·redis·后端·缓存·rocketmq·stream·队列
现在,此刻3 小时前
flink学习与如何在springboot项目中使用flink
spring boot·学习·flink
Cosmoshhhyyy4 小时前
《Effective Java》解读第5条:优先考虑依赖注入来引用资源
java
.柒宇.5 小时前
力扣hot100----15.三数之和(java版)
java·数据结构·算法·leetcode
程序员卷卷狗5 小时前
JVM 调优实战:从线上问题复盘到精细化内存治理
java·开发语言·jvm
cj6341181506 小时前
【MySQL】mysqldump使用方法
java·后端
JIngJaneIL6 小时前
停车场管理|停车预约管理|基于Springboot的停车场管理系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·后端·论文·毕设·停车场管理系统
杰克尼6 小时前
二分查找为什么总是写错
java·数据结构·算法
半旧夜夏8 小时前
【分布式缓存】Redis持久化和集群部署攻略
java·运维·redis·分布式·缓存
短视频矩阵源码定制8 小时前
矩阵系统源码推荐:技术架构与功能完备性深度解析
java·人工智能·矩阵·架构