【问题标题】:RxJS: Send x requests per secondRxJS:每秒发送 x 个请求
【发布时间】:2015-09-26 00:50:24
【问题描述】:

我有函数createEvent() 向谷歌日历发送请求。

Google 日历的 API 要求我每秒最多发送 5 个请求。

如果我拨打createEvent() 100 次,它将淹没谷歌日历并且我的请求被拒绝。如果可能的话,我希望 createEvent() 包含将请求限制为每秒 5 次所需的逻辑。

我尽量避免,

calendar.addEventToQueue(eventData);
calendar.addEventToQueue(eventData);
calendar.addEventToQueue(eventData);
cleandar.submitEvents();

而只是

calendar.createEvent(eventData);
calendar.createEvent(eventData);
calendar.createEvent(eventData);

【问题讨论】:

    标签: javascript http asynchronous reactive-programming rxjs


    【解决方案1】:

    我想我不久前在rate limiting 上给出了这个答案。

    你可以用 RxJS 做到这一点:

    //This would be replaced by whatever your event source was
    //I just made it a button click in this case
    var source = Rx.Observable.fromEvent($button, 'click')
    
      //Captures either all the events for one second for a max of 5 events
      //Projects each set into an Observable
      .windowWithTimeOrCount(1000, 5)
    
      //Only the first window in a single second gets propagated
      //The others will be dropped
      .throttleFirst(1000)
    
      //Flatten the sequence by concatenating all the windows
      .concatAll()
    
      //Build the event body now *after* we have done filtering
      .flatMap(function() { 
        //The calendar request api supports promises which are 
        //handled implicitly in Rx by operators like flatMap. As a result
        //this will automatically wait until it receives a response.
        return gapi.client.calendar.events.insert(/*event body*/);
      });
    
    //Process the response
    source.subscribe(
      function(response) { console.log('Event successfully created!'); });
    

    【讨论】:

    • 非常感谢您的回答,这真的很有帮助。问题,throttleFirst 在节点中的requrie('rx') 中不存在。有什么建议吗?
    • 忘了它是 3.1.2 中的 deprecated。现在它被称为throttle
    • 感谢@paulpdaniels,我的事件源是事件请求流。如果它们超过每秒 5 个 throttle,则应该缓冲(延迟),似乎正在丢弃额外的事件并只保留第一个输出。
    • @DanielRasmuson 您将需要使用背压运算符而不是节流阀。在我提供的链接中,我还提出了一种实施规范的方法。
    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 2021-01-17
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多