我怎样才能使用 puppeteer 作为 cachewarmer?

How can I use puppeteer for cachewarmer?

我有一个包含 ~1000 个 url 的长 txt 文件,需要执行它来预热 varnish 缓存。
由于我需要人偶操纵者,是否存在通过 AJAX 调用加载的重要内容。

这是我的第一次尝试,但不是 node 的高手。
真正的问题是它产生了 100% 的负载,并启动了太多线程。

const puppeteer = require('puppeteer');
const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
    input: fs.createReadStream('varnish-warmer.txt')
  });

rl.on('line', (line) => {
(async () => {
    if (line != '') {
    const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(line);
        await page.waitFor(1000);

        browser.close();
    }

})();
});

正如您已经注意到的,您的代码会并行启动所有浏览器,这会使您的系统过载。您可以一个接一个地访问每个 URL(选项 1)或使用 pool of browsers 来加快进程(选项 2)。

选项 1

启动一个浏览器并依次访问所有页面:

const puppeteer = require('puppeteer');
const fs = require('fs');

const lines = fs.readFileSync('varnish-warmer.txt').toString().split('\n');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    for (const line of lines) {
        await page.goto(line);
        await page.waitFor(1000);
    }
    await browser.close();
})();

选项 2

由于选项 1 可能需要 1000 URL 秒,您可能希望使用浏览器池来并行访问页面并加快速度。您可以为此使用 puppeteer-cluster(免责声明:我是图书馆的作者)。

const { Cluster } = require('puppeteer-cluster');
const fs = require('fs');

(async () => {
    const cluster = await Cluster.launch({
        concurrency: Cluster.CONCURRENCY_BROWSER,
        maxConcurrency: 10, // how many URLs should be visited in parallel
        // monitor: true, // uncomment to see information about progress
    });

    // Define the task for each URL
    await cluster.task(async ({ page, data: url }) => {
        await page.goto(url);
        await page.waitFor(1000);
    });

    // Queue the URLs
    const lines = fs.readFileSync('varnish-warmer.txt').toString().split('\n');
    lines.forEach(line => cluster.queue(line));

    // Wait for the tasks to finish and close the cluster after that
    await cluster.idle();
    await cluster.close();
})();

您可以根据系统的能力 (CPU/memory) 调整 maxConcurrency 的值来更改工作人员的数量。