OkHttp API 速率限制 [英] OkHttp API rate limit

查看:121
本文介绍了OkHttp API 速率限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OkHttp 是一种符合 api 速率请求限制的集成方式,还是必须在外部实现?无论哪种情况,我们都欢迎您提供有关从哪里开始的提示.

Has OkHttp an integrated way of complying with an api rate request limit, or it has to be implemented externally? either case a hint on where to start is appreciated.

推荐答案

拦截器结合来自 Guava 的 RateLimiter 是避免接收 429 HTTP 代码的一个很好的解决方案.

An interceptor combined with a RateLimiter from Guava was a good solution to avoid receiving a 429 HTTP code.

假设我们希望限制为每秒 3 次调用:

Let's suppose we want a limit of 3 calls per second:

import java.io.IOException;

import com.google.common.util.concurrent.RateLimiter;

import okhttp3.Interceptor;
import okhttp3.Response;

public class RateLimitInterceptor implements Interceptor {
    private RateLimiter rateLimiter = RateLimiter.create(3);

    @Override
    public Response intercept(Chain chain) throws IOException {
        rateLimiter.acquire(1);
        return chain.proceed(chain.request());
    }
}

这篇关于OkHttp API 速率限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆