如何使ExpressJS支持像Facebook这样的批处理请求 [英] How to make expressjs support batch request like facebook

查看:37
本文介绍了如何使ExpressJS支持像Facebook这样的批处理请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组使用不同方法的路线.我想让expressjs支持与Facebook非常相似的批处理请求, Facebook批处理请求.有人知道怎么做吗?而且我不想建立3个回送连接来处理批处理请求.

I have a set of routes with different methods. I want to make the expressjs to support batch request which is very similar to facebook, Facebook Batch Request. Does anybody know how to do it? And I dont want to make 3 loopback connections for handling the batch request.

推荐答案

如果您不想建立环回连接,那么最简单的解决方案是使用虚假请求手动调用服务器.

If you don't want to make loopback connections, then the simplest solution is to manually call your server with fake requests.

您必须重新实现 IncomingMessage .您还应该使用 Async#map 等待所有请求都被处理.

You'll have to reimplement IncomingMessage. You should also use Async#map to wait until all requests are processed.

这是基本概念:


// You'll probably have more work to do to reimplement http basic API.
function FakeRequest(request) {
  this.url = '/' + request.relative_url;
  this.method = request.method;
  this.headers = request.headers;
}

function FakeResponse() {
  Stream.call(this);

  this.statusCode = null;
  this.body = '';
}

FakeResponse.prototype.write = function (chunk) {
  this.body += chunk.toString('utf8');

  return true;
};

util.inherits(FakeResponse, Stream);

app.post('/', function (req, res) {
  var requests = JSON.parse(req.body.batch);

  async.map(requests, function (request, done) {
    var fakeReq = new FakeRequest(request),
        fakeRes = new FakeResponse();

    // call Express' middleware manually
    app(fakeReq, fakeRes);

    // this will trigger when the response is ready.
    fakeRes.once('end', function () {
      // don't leak listeners
      fakeRes.removeAllListeners();
      done(null, fakeRes);
    });

    fakeRes.once('error', function (err) {
      fakeRes.removeAllListeners();
      done(err);
    });
  }, function (err, responses) {
    if (err)
      return res.send(err);

    res.send(responses);
  });
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

更新

我实际上不确定环回的含义,但是您有2种选择:

I'm actually not sure what you mean by loopback, but you have 2 options:

  • 为批处理中的每个请求打开一个HTTP连接,该连接易于实现,但速度较慢.

  • Open an HTTP connection for each request in the batch, which is easier to implement but slower.

我上面概述的解决方案:在不打开HTTP请求的情况下直接调用Express中间件.

The solution I outlined above: call the Express middleware directly without opening HTTP requests.

给我的印象是您不想要第一个解决方案.但是,即使速度较慢,这也是我会首先尝试的方法:

I was under the impression that you didn't want the first solution. However, that's what I would try first, even if it's slower:

  • 扩展规模时,更容易在多个实例之间分布批处理连接.
  • 您将不会绕过您可能拥有的任何负载限制机制(防止单个Express实例同时处理太多请求).

请务必禁用 HTTP代理.

这篇关于如何使ExpressJS支持像Facebook这样的批处理请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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