You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js对SSE服务进行并发连接负载测试?

如何对SSE长连接接口做负载测试

针对你提供的SSE(Server-Sent Events)接口,以下是几种实用的负载测试方案,用来验证服务器能承载的最大并发长连接数:

一、用wrk工具测试

wrk是轻量高效的HTTP基准测试工具,需要配合Lua脚本模拟长连接行为:

  1. 编写Lua脚本(命名为sse_test.lua):
function request()
    return wrk.format("GET", "/stream", {
        ["Accept"] = "text/event-stream",
        ["Cache-Control"] = "no-cache",
        ["Connection"] = "keep-alive"
    })
end

function response(status, headers, body)
    -- 保持连接不主动关闭
    return true
end
  1. 执行测试命令:
wrk -t4 -c1000 -d30s -s sse_test.lua http://你的服务器地址:端口

参数说明:

  • -t4:启用4个测试线程
  • -c1000:模拟1000个并发连接
  • -d30s:测试持续30秒
  • -s:指定刚才编写的Lua脚本

二、用Artillery测试

Artillery是更易用的Node.js负载测试工具,适合快速生成测试场景:

  1. 安装Artillery:
npm install -g artillery
  1. 创建配置文件(命名为load-test.yml):
config:
  target: "http://你的服务器地址:端口"
  phases:
    - duration: 60
      arrivalRate: 50
      name: "逐步加压"
  defaults:
    headers:
      Accept: "text/event-stream"
      Cache-Control: "no-cache"
scenarios:
  - name: "维持SSE长连接"
    flow:
      - get:
          url: "/stream"
          keepalive: true
          timeout: 300
  1. 启动测试:
artillery run load-test.yml

测试过程中会实时输出并发数、响应状态、错误率等指标。

三、自定义Node.js测试脚本

如果需要更灵活的控制逻辑,可以自己写脚本模拟并发连接:

创建test-sse.js:

const http = require('http');

// 配置参数
const TOTAL_CONNECTIONS = 1000;
const TARGET_URL = 'http://你的服务器地址:端口/stream';
const CONNECTION_INTERVAL = 10; // 每隔10ms创建一个连接,避免瞬间压服

let activeConnections = 0;
let closedConnections = 0;

function createConnection() {
    const req = http.get(TARGET_URL, {
        headers: {
            'Accept': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
        }
    });

    req.on('response', (res) => {
        activeConnections++;
        console.log(`已建立连接:${activeConnections}/${TOTAL_CONNECTIONS}`);

        // 监听数据,避免连接被自动关闭
        res.on('data', () => {});

        res.on('close', () => {
            closedConnections++;
            console.log(`连接关闭:${closedConnections}`);
        });
    });

    req.on('error', (err) => {
        console.error(`连接失败:${err.message}`);
    });
}

// 批量创建连接
for (let i = 0; i < TOTAL_CONNECTIONS; i++) {
    setTimeout(createConnection, i * CONNECTION_INTERVAL);
}

// 定时输出当前活跃连接数
setInterval(() => {
    console.log(`当前活跃连接:${activeConnections - closedConnections}`);
}, 5000);

运行脚本:

node test-sse.js

四、测试关键注意事项

  • 调整系统与Node.js参数:Linux系统默认文件描述符上限较低,先执行ulimit -n 65535放开限制;Node.js启动时可加--max-old-space-size=4096调整内存上限。
  • 逐步加压测试:从低并发(如100)开始,逐步提升到500、1000,观察服务器CPU、内存、连接数变化,直到出现错误或性能骤降。
  • 监控核心指标:测试时用netstat -an | grep ESTABLISHED | wc -l查看服务器当前开放连接数,同时监控CPU使用率、内存占用,定位瓶颈。
  • 避免网络瓶颈:尽量让测试机和服务器在同一局域网内,排除带宽限制对测试结果的影响。

内容的提问来源于stack exchange,提问作者Hasancan Çakıcıoğlu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:15:15