OkHttp是否有符合接口请求速率限制的集成方式,或者必须在外部实现?无论哪种情况,都希望能给出一个从哪里开始的提示。
发布于 2019-09-12 23:28:11
interceptor与来自Guava的RateLimiter相结合是避免接收429HTTP代码的好解决方案。
假设我们想要限制每秒3次调用:
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());
}
}发布于 2018-09-11 21:15:19
正如@jesse-威尔逊所说,你可以用OkHttp Interceptors做到这一点
下面是一个例子。首先定义一个自定义的拦截器。当达到速率限制时,我调用的api以HTTP代码429响应。您将需要在您自己的api中检查指示速率错误的特定HTTP代码或标头,并在适当的时间休眠。
public class RateLimitInterceptor implements Interceptor {
public RateLimitInterceptor() {
}
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// 429 is how the api indicates a rate limit error
if (!response.isSuccessful() && response.code() == 429) {
System.err.println("Cloudant: "+response.message());
// wait & retry
try {
System.out.println("wait and retry...");
Thread.sleep(1000);
} catch (InterruptedException e) {}
response = chain.proceed(chain.request());
}
return response;
}
}接下来,将拦截器添加到构建OkHttp请求的位置。这是我的构建器的一个例子。
public static Response fetchPaged(HttpUrl url) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.addInterceptor(new RateLimitInterceptor())
.build();
Request request = new Request.Builder()
.url(url)
.build();
return client
.newCall(request)
.execute();
}发布于 2016-02-13 04:44:28
您可以构建一个interceptor来跟踪发出的请求,并在请求速率过高时潜在地限制或失败请求。
https://stackoverflow.com/questions/35364823
复制相似问题