ChelesteWang / FE-Review

前端知识复盘与整理
Apache License 2.0
33 stars 8 forks source link

Puppeteer 性能问题复盘 #1

Open ChelesteWang opened 3 years ago

ChelesteWang commented 3 years ago

因为 Chromium 消耗最多的资源是 CPU,当并发数变高时,CPU 也随之变高,就会导致后面的绘制变慢。

const browser = await puppeteer.launch({
  args: [
    '–disable-gpu',
    '–disable-dev-shm-usage',
    '–disable-setuid-sandbox',
    '–no-first-run',
    '–no-sandbox',
    '–no-zygote',
    '–single-process'
  ]
});

关闭无用的 chromium 的功能,启用单标签与单进程

const page = await browser.newPage();
page.setContent(html, {
  waitUntil: 'networkidle0'
});

const imageBuffer = await page.screeshot(options);
ChelesteWang commented 3 years ago

2 使用 autocannon 进行并发测试

ChelesteWang commented 3 years ago

参考链接

使用 Puppeteer 搭建统一海报渲染服务 Puppeteer 用来做爬虫太 Low 了!但用在这里很合适! 自动化 Web 性能分析之 Puppeteer 爬虫实践 Puppeteer自动化的性能优化与执行速度提升 puppeteer使用问题总结

ChelesteWang commented 3 years ago

服务器端架构使用的都是常用配置,通过PM2生成多个Node实例,Chrome Headless本身支持多实例(理论 上在资源足够多的情况下我们可以打开无数个Chrome浏览器)。Chrome Headless的执行是同步的,Node服务本身是异步的,所以多个实例并不能支持更大的并发,只是可以利用多核CPU。这里PM2生成4个实例和生成一个实例的差异并不大。接口的瓶颈在于 Chrome Headless 的执行速度与内存、CPU等资源的消耗情况。

  1. Chrome Headless版本选择

    在tlinux上chromium有多个版本可以选择,经过我的测试,最优的版本是:

    ```shell $ yum install chromium-headless $ /usr/lib64/chromium-browser/headless_shell (调用路径) ```
  2. 主要优化点

    • 浏览器每次调用后一定要关闭。否则一个page页面发生错误,整个服务都会卡死。
    • 浏览器打开时会默认有一个page页面,直接利用该页面能减少1/3左右的内存消耗。