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 调用的接口
}
相关推荐
甜甜的资料库4 分钟前
基于微信小程序的作业管理系统源码数据库文档
java·数据库·微信小程序·小程序
有梦想的骇客6 小时前
书籍“之“字形打印矩阵(8)0609
java·算法·矩阵
yours_Gabriel6 小时前
【java面试】微服务篇
java·微服务·中间件·面试·kafka·rabbitmq
hashiqimiya8 小时前
android studio中修改java逻辑对应配置的xml文件
xml·java·android studio
liuzhenghua668 小时前
Python任务调度模型
java·运维·python
結城8 小时前
mybatisX的使用,简化springboot的开发,不用再写entity、mapper以及service了!
java·spring boot·后端
小前端大牛马8 小时前
java教程笔记(十一)-泛型
java·笔记·python
Bruk.Liu8 小时前
《Minio 分片上传实现(基于Spring Boot)》
前端·spring boot·minio
东阳马生架构8 小时前
商品中心—2.商品生命周期和状态的技术文档
java
星辰离彬9 小时前
Java 与 MySQL 性能优化:MySQL 慢 SQL 诊断与分析方法详解
java·spring boot·后端·sql·mysql·性能优化