我该如何排队并延迟改造请求以避免达到api速率限制? [英] How can I queue up and delay retrofit requests to avoid hitting an api rate limit?

查看:72
本文介绍了我该如何排队并延迟改造请求以避免达到api速率限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实现节流的API.限制之一是每秒1个请求.啊.我遇到以下情况,马上就达到了极限.

I'm using an api that implements throttling. One of the limits is 1 request/second. ugh. I have the following scenario which hits the limit right away.

  • 使用api/status检查api的状态

  • Check the status of the api with api/status

如果api已启动,请获取用户订阅

if the api is up, get a users subscriptions

从订阅列表中加载页面

有什么我可以插入改造中的东西,它可以将每个网络请求排队,使其仅在最后一个请求之后至少运行1000毫秒?我正在使用/学习rxjava,在这里 debounce 可以有用吗?

Is there anything I can plug into retrofit that can queue each network request to only run at least 1000ms after the last? I am using/learning rxjava, can debounce be of any use here?

推荐答案

您可以限制可观察的内容.

You can throttle your observable.

    Observable<String> text = ...
text.throttleLast(1, SECONDS)
    .flatMap(retrofitApiCall())
    .subscribe(result -> System.out.println("result: " + result));

另一种解决方案是在okhttp构建器中设置一个调度程序,并添加一个睡眠一秒钟的拦截器.这可能不是最优雅的解决方案,并且因为它一次将您限制在一个线程内,所以扼杀了使用异步的一些好处.

Another solution is to set a dispatcher in your okhttp builder, and add an interceptor that sleeps for one second. This may not be the most elegant solution and kills some of the benefits of using async because it limits you to one thread at a time.

OkHttpClient.Builder builder = new OkHttpClient.Builder();


    Dispatcher dispatcher = new Dispatcher();
    dispatcher.setMaxRequests(1);

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            SystemClock.sleep(1000);
            return chain.proceed(chain.request());
        }
    };

    builder.addNetworkInterceptor(interceptor);
    builder.dispatcher(dispatcher);
    builder.build();

这篇关于我该如何排队并延迟改造请求以避免达到api速率限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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