PHP项目压力测试如何模拟高并发

wen PHP项目 32

本文目录导读:

PHP项目压力测试如何模拟高并发

  1. 核心工具选择
  2. PHP代码优化(关键)
  3. 模拟真实并发场景
  4. 性能瓶颈定位
  5. 生产环境压测建议
  6. 实战示例(完整压测流程)
  7. 注意事项

为 PHP 项目模拟高并发压力测试,推荐使用 SwooleWorkerman 等常驻内存框架,配合专业压测工具,以下是完整方案:

核心工具选择

Apache Bench (ab) - 快速简单

# 模拟1000并发,发送2000请求
ab -n 2000 -c 1000 http://your-api.com/test

wrk - 高性能压测

# 使用4线程,保持100连接,持续30秒
wrk -t4 -c100 -d30s http://your-api.com/test

Siege - 多功能压测

# 并发50用户,持续60秒
siege -c50 -t60s http://your-api.com/test

JMeter - 图形化专业工具

  • 配置线程组(并发数)
  • 添加 HTTP 请求采样器
  • 设置持续时间和循环次数

PHP代码优化(关键)

<?php
// 使用 Swoole 构建高并发服务
$http = new Swoole\Http\Server("0.0.0.0", 9501);
$http->set([
    'worker_num' => 4,          // 根据CPU核心数设置
    'max_request' => 10000,     // 热重启
    'dispatch_mode' => 2,       // 固定分配
]);
$http->on('request', function ($request, $response) {
    // 业务逻辑
    $response->end("Hello World");
});
$http->start();

模拟真实并发场景

场景1:瞬时高并发(秒杀)

# 同时启动100个并发请求
seq 1 100 | xargs -I {} -P 100 curl http://localhost:9501/test &

场景2:持续压力测试

// Python 并发脚本示例
import threading
import requests
def stress_test():
    while True:
        try:
            r = requests.get('http://localhost:9501/test')
            print(f"Status: {r.status_code}")
        except:
            pass
# 启动50个线程
threads = [threading.Thread(target=stress_test) for _ in range(50)]
[t.start() for t in threads]

性能瓶颈定位

实时监控资源

# 每秒刷新系统状态
watch -n1 'netstat -ant | grep :80 | wc -l; echo "---"; top -bn1 | grep PHP'

数据库连接池

// Swoole 连接池示例
$pool = new Swoole\Database\MysqliPool([
    'host' => '127.0.0.1',
    'user' => 'root',
    'password' => '',
    'database' => 'test',
    'max_connections' => 100,  // 根据并发数调整
]);

生产环境压测建议

渐进式增加并发

# 从50并发开始,每次增加50
for c in 50 100 200 500; do
    ab -n 10000 -c $c http://localhost/test
    sleep 2
done

监控关键指标

  • QPS (每秒查询数)
  • 响应时间 (p50/p95/p99)
  • 错误率
  • 内存使用

优化PHP配置

; php.ini
max_execution_time = 30
memory_limit = 256M
; 开启OPcache
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 10000

实战示例(完整压测流程)

# 1. 启动优化后的服务
php -S 0.0.0.0:8080 -t public server.php
# 2. 预热OPcache
ab -n 1000 -c 10 http://localhost:8080/api/users
# 3. 正式压测(模拟1000并发)
wrk -t8 -c1000 -d60s --latency http://localhost:8080/api/users
# 4. 分析结果
# 关注:Requests/sec, Latency Distribution

注意事项

  1. 不要压测生产环境:使用测试或预发布环境
  2. 观察连接池数量:避免数据库连接耗尽
  3. 使用本地网络:排除网络延迟干扰
  4. 逐步增加负载:找到系统瓶颈点
  5. 记录所有数据:包括服务器资源使用情况

对于传统PHP(非Swoole),建议使用 Nginx + PHP-FPM 架构,压测前先调整 PHP-FPM 配置:

; www.conf
pm = dynamic
pm.max_children = 150
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 500

通过这种组合方案,你可以在安全的前提下,准确测试PHP项目的高并发处理能力。

抱歉,评论功能暂时关闭!