Artillery 负载测试工具教程

Artillery 是一款基于 Node.js 的现代化负载测试工具,支持 HTTP、WebSocket、Socket.IO 等多种协议。它使用 YAML 文件定义测试场景,语法简洁直观,能够快速构建复杂的测试用例。在搬瓦工 VPS 上部署 Artillery 可以方便地对各种 Web 服务进行性能压测和瓶颈分析。

一、安装 Artillery

1.1 安装 Node.js

apt update && apt upgrade -y
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install nodejs -y
node --version

1.2 安装 Artillery

npm install -g artillery
artillery version

二、快速开始

2.1 快速测试

Artillery 提供了 quick 命令,无需编写配置文件即可进行简单测试:

# 10 个虚拟用户,每秒创建 1 个,持续 10 秒
artillery quick --count 10 --num 1 https://your-target-site.com

2.2 编写测试脚本

创建 test.yml 文件:

config:
  target: "https://your-target-site.com"
  phases:
    - duration: 60
      arrivalRate: 5
      name: "预热阶段"
    - duration: 120
      arrivalRate: 20
      name: "正常负载"
    - duration: 60
      arrivalRate: 50
      name: "峰值负载"

scenarios:
  - name: "浏览首页"
    flow:
      - get:
          url: "/"
      - think: 2
      - get:
          url: "/about"

运行测试:

artillery run test.yml

三、测试场景配置

3.1 POST 请求和 JSON 数据

config:
  target: "https://api.example.com"
  phases:
    - duration: 60
      arrivalRate: 10

scenarios:
  - name: "API 测试"
    flow:
      - post:
          url: "/api/login"
          json:
            username: "testuser"
            password: "testpass"
          capture:
            - json: "$.token"
              as: "authToken"
      - get:
          url: "/api/dashboard"
          headers:
            Authorization: "Bearer {{ authToken }}"
      - post:
          url: "/api/data"
          headers:
            Authorization: "Bearer {{ authToken }}"
          json:
            title: "Test Entry"
            content: "Load testing content"

3.2 使用 CSV 数据

通过外部 CSV 文件提供测试数据,模拟不同用户行为:

config:
  target: "https://your-target-site.com"
  phases:
    - duration: 60
      arrivalRate: 10
  payload:
    path: "users.csv"
    fields:
      - "username"
      - "password"
    order: "sequence"

scenarios:
  - name: "多用户登录测试"
    flow:
      - post:
          url: "/api/login"
          json:
            username: "{{ username }}"
            password: "{{ password }}"

CSV 文件格式:

user1,pass1
user2,pass2
user3,pass3

3.3 WebSocket 测试

config:
  target: "wss://ws.example.com"
  phases:
    - duration: 30
      arrivalRate: 5

scenarios:
  - engine: ws
    flow:
      - send: '{"type": "subscribe", "channel": "updates"}'
      - think: 5
      - send: '{"type": "message", "content": "hello"}'
      - think: 3

四、高级配置

4.1 阶段性负载

config:
  target: "https://your-target-site.com"
  phases:
    - duration: 30
      arrivalRate: 1
      rampTo: 10
      name: "渐增阶段"
    - duration: 120
      arrivalRate: 10
      name: "稳定阶段"
    - duration: 30
      arrivalRate: 10
      rampTo: 50
      name: "压力阶段"
    - duration: 30
      arrivalRate: 50
      rampTo: 1
      name: "降压阶段"

4.2 响应验证

scenarios:
  - name: "验证响应"
    flow:
      - get:
          url: "/api/health"
          expect:
            - statusCode: 200
            - contentType: json
            - hasProperty: status
      - get:
          url: "/api/users"
          expect:
            - statusCode: 200
            - hasHeader: "content-type"

4.3 自定义函数

创建 helpers.js 辅助函数文件:

module.exports = {
  generateRandomUser: function(userContext, events, done) {
    const id = Math.floor(Math.random() * 10000);
    userContext.vars.userId = id;
    userContext.vars.username = `user_${id}`;
    return done();
  },

  logResponse: function(requestParams, response, context, ee, next) {
    if (response.statusCode >= 400) {
      console.log(`错误: ${response.statusCode} - ${requestParams.url}`);
    }
    return next();
  }
};

在测试脚本中引用:

config:
  target: "https://your-target-site.com"
  processor: "./helpers.js"
  phases:
    - duration: 60
      arrivalRate: 10

scenarios:
  - name: "自定义函数测试"
    flow:
      - function: "generateRandomUser"
      - post:
          url: "/api/users"
          afterResponse: "logResponse"
          json:
            id: "{{ userId }}"
            name: "{{ username }}"

五、生成测试报告

5.1 JSON 报告

artillery run test.yml --output report.json

5.2 HTML 报告

artillery run test.yml --output report.json
artillery report report.json --output report.html

生成的 HTML 报告包含可视化图表,展示响应时间分布、RPS 趋势和错误率等指标。

六、使用 Docker 运行

mkdir -p /opt/artillery && cd /opt/artillery

# 将测试文件放入目录后运行
docker run --rm -v $(pwd):/scripts \
  artilleryio/artillery:latest \
  run /scripts/test.yml --output /scripts/report.json

七、常见问题

连接超时

在配置中增加超时设置:

config:
  target: "https://your-target-site.com"
  http:
    timeout: 30
    pool: 100

系统资源限制

ulimit -n 65535
sysctl -w net.core.somaxconn=65535
sysctl -w net.ipv4.tcp_max_syn_backlog=65535

总结

Artillery 以其简洁的 YAML 语法和丰富的协议支持,成为 Node.js 生态中优秀的负载测试工具。在搬瓦工 VPS 上可以轻松部署并运行各种压力测试场景。选购搬瓦工 VPS 请参考 全部方案,购买时使用优惠码 NODESEEK2026 可享受 6.77% 折扣。更多测试工具可参考 Locust 教程Vegeta 教程

关于本站

搬瓦工VPS中文网(bwgvps.com)是非官方中文信息站,整理搬瓦工的方案、优惠和教程。我们不销售主机,不提供技术服务。

新手必读
搬瓦工优惠码

NODESEEK2026(优惠 6.77%)

购买时填入即可抵扣。