CouchDB -使用jQuery进行连续馈送

oymdgrw7  于 2022-12-09  发布在  CouchDB
关注(0)|答案(2)|浏览(158)

在阅读了类似的问题here后,我很好奇这是否完全可能?
我知道我可以通过 Package 一个setInterval函数(它重复调用check-for-changes函数)来使下面的代码工作,但是我更愿意使用连续轮询。
数据库在高峰期每分钟都会定期更新,但在非高峰期持续轮询数据库似乎是一种浪费...

$.getJSON('http://localhost:5984/db?callback=?', function(db) {
    console.log(db.update_seq);
    $.getJSON('http://localhost:5984/db/_changes?since='+db.update_seq+'&feed=continuous&callback=?', function(changes) {
        console.log(changes);
    });
});

Firebug显示当确实进行了更改时,会发生一些事情,但只返回null。
我也在同一个域上,从localhost/index.php调用一个页面

czq61nw1

czq61nw11#

您可以采用自适应策略,而不是使用连续或长时间轮询。可能以1分钟的间隔开始。如果没有更新,则最多2分钟,然后3、4、5等。如果有一些更新,则可以修改间隔以反映到下一次预期更新的时间。
基本上,这一切都归结为它是多么重要,你实际上得到的更新通知,在近实时和多大的延迟,你愿意处理。

xdnvmnnf

xdnvmnnf2#

下面是一个Colin Ross的可接受答案的具体示例:

(function($) {
  // this is a recursive function
  function longpoll(database, last_seq) {
    var url = "/" + database + "/_changes?feed=longpoll";
    // If we don't have a sequence number, then see where we are up to.
    if (last_seq) {
      url = url + "&since=" + last_seq;
    }
    $.ajax({
      type: "GET",
      url: url,
      dataType: 'json',
      success: function(data) {
        // Now we need to see what to do with the data.
        console.log(document.data.results);

        // And set up the re-run of the fetch query.
        // recursive call
        longpoll(database, data.last_seq);
      }
    })
  }
  
  $.couch.longpoll = longpoll;
}(jQuery));

此示例源代码来自现已归档的博客:https://web.archive.org/web/20170821130003/http://schinckel.net/2012/01/22/jquery-long-poll-for-couchdb-changes./

相关问题