Laravel接口压测怎么做

wen PHP项目 1

本文目录导读:

Laravel接口压测怎么做

  1. 使用 Apache Bench (ab)
  2. 使用 wrk
  3. 使用 siege
  4. Laravel 项目优化配合
  5. 压测报告分析
  6. 高级压测方案
  7. 压测最佳实践
  8. 示例:完整压测脚本

Laravel接口压测的几种主流方案:

使用 Apache Bench (ab)

# 基本用法
ab -n 1000 -c 100 http://your-domain.com/api/users
# 参数说明
-n 1000    # 总请求数
-c 100     # 并发数
-k         # 启用KeepAlive
-t 60      # 测试持续时间(秒)

使用 wrk

# 安装
brew install wrk  # macOS
apt-get install wrk  # Ubuntu
# 基本用法
wrk -t12 -c400 -d30s http://your-domain.com/api/users
# 使用POST请求
wrk -t12 -c400 -d30s \
    -H "Content-Type: application/json" \
    -s post.lua \
    http://your-domain.com/api/login

使用 siege

# 安装
brew install siege
# 基本用法
siege -c 100 -r 10 http://your-domain.com/api/users
# 带POST请求
siege -c 100 -r 10 \
    -H "Content-Type: application/json" \
    -f urls.txt

Laravel 项目优化配合

1 环境配置优化

// .env 文件
APP_ENV=production
APP_DEBUG=false
APP_URL=http://your-domain.com
# 缓存配置
CACHE_DRIVER=redis
SESSION_DRIVER=redis

2 优化命令

# 清除并缓存配置
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize
# 生成类映射加载优化
composer dump-autoload -o

压测报告分析

1 ab 结果解读

Completed 1000 requests    # 已完成请求数
Request per second: 500.43  # 每秒请求数
Time per request: 199.82ms  # 每个请求平均时间
Failed requests: 0          # 失败请求数
Transfer rate: 2.45 MB/s    # 传输速率

2 关注指标

  • RPS (Requests Per Second):每秒请求数
  • 响应时间:平均、中位数、P99等
  • 错误率:超时、连接失败等
  • 吞吐量:网络传输速率

高级压测方案

1 使用 k6 (推荐)

// test.js
import http from 'k6/http';
import { sleep, check } from 'k6';
export const options = {
    vus: 100,  // 虚拟用户数
    duration: '30s',  // 测试时长
    thresholds: {
        http_req_duration: ['p(95)<2000'],  // 95%请求应在2秒内
    },
};
export default function () {
    const res = http.get('http://your-domain.com/api/users');
    check(res, {
        'status is 200': (r) => r.status === 200,
        'response time < 500ms': (r) => r.timings.duration < 500,
    });
    sleep(1);
}
k6 run test.js

2 使用 Locust (Python)

# locustfile.py
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
    wait_time = between(1, 5)  # 用户等待时间
    @task(3)  # 权重
    def view_users(self):
        response = self.client.get("/api/users")
        if response.status_code != 200:
            response.failure("Got wrong response")
    @task(1)
    def create_user(self):
        self.client.post("/api/users", json={
            "name": "test",
            "email": "test@example.com"
        })
locust -f locustfile.py --host=http://your-domain.com

压测最佳实践

1 准备工作

# 1. 开启Laravel性能优化
php artisan config:cache
php artisan route:cache
php artisan view:cache
# 2. 使用Redis作为缓存和session驱动
# 3. 数据库添加索引
# 4. 开启OPcache

2 注意事项

  1. 渐进式加压:从低并发开始逐步增加
  2. 监控系统资源:CPU、内存、IO
  3. 分开测试:不同接口分别压测
  4. 模拟真实场景:考虑用户登录态、token等
  5. 预热:先跑少量请求让系统预热

3 常见瓶颈识别

# 查看数据库慢查询
mysql> SHOW FULL PROCESSLIST;
mysql> SET GLOBAL slow_query_log = 'ON';
# 查看PHP日志
tail -f storage/logs/laravel.log
# 查看系统资源
top -bn1 | head -5
iostat -x 1

示例:完整压测脚本

#!/bin/bash
# 压测脚本 benchmark.sh
URL=$1
CONCURRENCY=${2:-100}
REQUESTS=${3:-1000}
echo "Starting benchmark for $URL"
echo "Concurrency: $CONCURRENCY"
echo "Total requests: $REQUESTS"
# 预热
ab -n 10 -c 5 $URL > /dev/null 2>&1
sleep 2
# 正式测试
ab -n $REQUESTS -c $CONCURRENCY -k $URL
echo "Benchmark completed"

推荐方案

  • 快速测试:abwrk
  • 复杂场景:k6Locust
  • 生产环境:专业压测平台 (JMeter, LoadRunner)

压测前确保在类似生产环境的配置下进行,并注意不要对生产环境造成影响。

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