【问题标题】:NodeJS HTTP Request QueueNodeJS HTTP 请求队列
【发布时间】:2019-03-16 02:31:17
【问题描述】:

我使用 puppeteer & node js (express) 创建了爬虫。这个想法是当服务器收到 http 请求时,我的应用程序将开始抓取页面。

问题是如果我的应用程序一次收到多个 http 请求。抓取过程将一遍又一遍地开始,直到没有 http 请求命中。我如何只启动一个 http 请求并将另一个请求排队,直到第一个抓取过程完成?

目前,我用下面的代码尝试了node-request-queue,但没有运气。

var express = require("express");
var app = express();
var reload = require("express-reload");
var bodyParser = require("body-parser");
const router = require("./routes");
const RequestQueue = require("node-request-queue");

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;

app.use(express.static("public")); // static assets eg css, images, js

let rq = new RequestQueue(1);

rq.on("resolved", res => {})
  .on("rejected", err => {})
  .on("completed", () => {});

rq.push(app.use("/wa", router));

app.listen(port);
console.log("Magic happens on port " + port);

【问题讨论】:

  • 为什么要将路由器推入请求队列?
  • 那么如何正确的做请求队列呢?对不起,我是新来表达的
  • 你能显示你实际刮板的代码吗?
  • 使用 RabbitMq 作为消息代理,并使您的抓取进程成为消费者。

标签: node.js express puppeteer


【解决方案1】:

node-request-queue 是为request 包创建的,与express 不同。

您可以使用最简单的承诺队列库p-queue 来完成队列。它具有并发支持,并且看起来比任何其他库都更具可读性。稍后您可以轻松地从 Promise 切换到像 bull 这样的健壮队列。

这是创建队列的方法,

const PQueue = require("p-queue");
const queue = new PQueue({ concurrency: 1 });

这就是你如何添加一个异步函数到队列中,如果你监听它,它将返回解析的数据,

queue.add(() => scrape(url));

因此,无需将路由添加到队列中,您只需删除它周围的其他线路并保持路由器原样。

// here goes one route
app.use('/wa', router);

在您的一个路由器文件中,

const routes = require("express").Router();

const PQueue = require("p-queue");
// create a new queue, and pass how many you want to scrape at once
const queue = new PQueue({ concurrency: 1 });

// our scraper function lives outside route to keep things clean
// the dummy function returns the title of provided url
const scrape = require('../scraper');

async function queueScraper(url) {
  return queue.add(() => scrape(url));
}

routes.post("/", async (req, res) => {
  const result = await queueScraper(req.body.url);
  res.status(200).json(result);
});

module.exports = routes;

确保将队列包含在路线中,而不是相反。在您的 routes 文件或您正在运行 scraper 的任何位置仅创建一个队列。

这里是爬虫文件的内容,你可以使用任何你想要的内容,这只是一个工作假人,

const puppeteer = require('puppeteer');

// a dummy scraper function
// launches a browser and gets title
async function scrape(url){
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(url);
  const title = await page.title();
  await browser.close();
  return title
}

module.exports = scrape;

使用 curl 的结果:

这里是my git repo,它有带有示例队列的工作代码。

警告

如果您使用任何这样的队列,您会注意到您在同时处理 100 个结果时遇到问题,并且对您的 api 的请求将不断超时,因为队列中还有 99 个其他 url 等待。这就是为什么您必须在以后了解更多关于真正的队列和并发的信息。

一旦你了解了队列的工作原理,其他关于 cluster-puppeteer、rabbitMQ、bull queue 等的答案将在那时对你有所帮助:)。

【讨论】:

  • 谢谢,这是清楚的解释。它可以帮助像我这样的 nodejs 初学者,因为 nodejs 中的队列与 RoR 中的不同。
  • 当我尝试这样做并 npm start 时,它不断弹出 p-queue 的 MODULE_NOT_FOUND 错误
  • @LeeBoonKong-你有解决办法吗?
【解决方案2】:

您可以为此使用puppeteer-cluster(免责声明:我是作者)。您可以设置一个只有一个工作人员池的集群。因此,分配给集群的作业会一个接一个地执行。

由于您没有说明您的 puppeteer 脚本应该做什么,因此在此代码示例中,我将提取页面标题作为示例(通过 /wa?url=... 提供)并将结果提供给响应。

// setup the cluster with only one worker in the pool
const cluster = await Cluster.launch({
    concurrency: Cluster.CONCURRENCY_CONTEXT,
    maxConcurrency: 1,
});

// define your task (in this example we extract the title of the given page)
await cluster.task(async ({ page, data: url }) => {
    await page.goto(url);
    return await page.evaluate(() => document.title);
});

// Listen for the request
app.get('/wa', async function (req, res) {
    // cluster.execute will run the job with the workers in the pool. As there is only one worker
    // in the pool, the jobs will be run sequentially
    const result = await cluster.execute(req.query.url);
    res.end(result);
});

这是一个最小的例子。您可能希望在侦听器中捕获任何错误。有关更多信息,请查看更复杂的示例,其中包含 screenshot server 在存储库中使用 express。

【讨论】:

  • 这对我在节点服务器上运行的 CPU 密集型 puppeteer 任务有很大帮助。能够使用您的工具将请求限制为最多 5 个。很棒的图书馆
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 2018-12-31
  • 2017-07-30
相关资源
最近更新 更多