温馨提示×

Linux环境下如何提升Laravel的并发能力

小樊
45
2025-12-30 02:34:03
栏目: 智能运维

Linux环境下提升 Laravel 并发能力的落地方案

一 系统层与网络内核调优

  • 提升文件句柄与进程数,避免 “too many open files”:
    • /etc/security/limits.d/www.conf
      • www-data soft nofile 1048576
      • www-data hard nofile 1048576
      • www-data soft nproc 65535
      • www-data hard nproc 65535
  • 增大连接队列、缩短端口占用时间、开启端口复用,提升高并发连接处理能力:
    • /etc/sysctl.d/99-tuning.conf
      • fs.file-max = 2097152
      • net.core.somaxconn = 65535
      • net.core.netdev_max_backlog = 65535
      • net.ipv4.tcp_max_syn_backlog = 65535
      • net.ipv4.ip_local_port_range = 1024 65535
      • net.ipv4.tcp_tw_reuse = 1
      • net.ipv4.tcp_fin_timeout = 15
      • net.ipv4.tcp_keepalive_time = 600
      • net.ipv4.tcp_keepalive_intvl = 30
      • net.ipv4.tcp_keepalive_probes = 5
      • vm.swappiness = 10
    • 使配置生效:sysctl --system
  • I/O 与内存:SSD 可选 noop/deadline 调度器;内存 ≤ 4GB 可配置约 8GB swap 避免 OOM。

二 PHP FPM 与 OPcache 关键配置

  • OPcache 建议(php.ini,按内存与代码量微调):
    • opcache.enable=1
    • opcache.enable_cli=1
    • opcache.memory_consumption=512M
    • opcache.interned_strings_buffer=64M
    • opcache.max_accelerated_files=10000
    • opcache.revalidate_freq=60
    • opcache.jit=tracing
    • opcache.jit_buffer_size=256M
  • FPM 进程模型与关键参数(/etc/php/*/fpm/pool.d/www.conf):
    • pm = dynamic/ondemand/static(按内存与并发选择)
    • pm.max_children、pm.start_servers、pm.min_spare_servers、pm.max_spare_servers 合理配比
    • request_terminate_timeout 与慢日志开启,避免长请求拖垮进程池
    • 生产关闭 cgi.fix_pathinfo=0
  • 自动加载优化:composer dump-autoload --optimize。

三 Web 服务器与 Laravel 框架层优化

  • Nginx 要点:
    • 静态资源直出并设置长期缓存;动态请求反代到应用
    • 开启 sendfile、tcp_nopush、tcp_nodelay;合理 keepalive_timeout
    • 示例片段:
      • location ~* .(ico|css|js|gif|jpe?g|png|svg|woff2?|ttf|map)$ {
        • access_log off; expires 30d; add_header Cache-Control “public, max-age=2592000, immutable”; try_files $uri =404;
        • }
      • location / { try_files $uri $uri/ @octane; }
      • location @octane {
        • proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr;
        • proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme;
        • proxy_read_timeout 60s; proxy_connect_timeout 3s; proxy_send_timeout 60s;
        • proxy_pass http://127.0.0.1:8000;
        • }
  • Laravel 生产化与缓存:
    • APP_ENV=production;APP_DEBUG=false
    • 执行缓存命令:php artisan config:cache、php artisan route:cache、php artisan view:cache
    • 查询优化:Eager Loading 预加载关联、为高频字段加索引、EXPLAIN 分析执行计划
    • 缓存与会话:CACHE_DRIVER=redis、SESSION_DRIVER=redis;热点数据用 Cache::remember 设置合理 TTL 并预热。

四 异步任务与常驻内存架构

  • 队列与异步:
    • 将邮件、图片处理等耗时任务放入队列,使用 Supervisor 守护 queue:work(Redis 驱动)
    • 示例 Supervisor 配置(/etc/supervisor/conf.d/laravel-queue.conf):
      • [program:laravel-queue]
      • command=php /path/to/artisan queue:work --sleep=3 --tries=3 --daemon
      • autostart=true;autorestart=true;user=www-data;numprocs=4
      • redirect_stderr=true;stdout_logfile=/path/to/storage/logs/queue.log
      • 执行:supervisorctl reread && supervisorctl update && supervisorctl start laravel-queue:*
  • 常驻内存提升吞吐(Laravel Octane + Swoole/RoadRunner):
    • 安装与初始化:composer require laravel/octane && php artisan octane:install
    • 运行与守护:php artisan octane:start --server=swoole(建议配合 Supervisor)
    • 参考参数(按硬件与业务调整):
      • OCTANE_WORKERS=16(如 8 核可先设 12–24
      • OCTANE_TASK_WORKERS=8
      • OCTANE_MAX_REQUESTS=10000
      • SWOOLE 选项:worker_num、task_worker_num、max_request、package_max_length、buffer_output_size、socket_buffer_size、enable_coroutine
    • Swoole 使用注意:避免 exit/die/dd、超全局变量;header/setcookie/flush 等不兼容用法需改为 Laravel 响应对象与中间件处理。

五 数据库与缓存策略及压测上线

  • 数据库优化:
    • 高频查询字段加索引、避免 N+1、必要时读写分离与连接数调优
    • 连接管理:合理配置最大连接数与超时;结合业务评估持久连接与连接池策略,避免超过数据库上限导致失败
  • 缓存策略:
    • 选择 Redis/Memcached 作为缓存后端;统一用 Cache Facade
    • 示例:CACHE_DRIVER=redis;热点数据 Cache::remember(‘key’, 3600, fn() { … })
    • 发布/变更后及时清理或重建缓存:php artisan cache:clear / config:clear / route:clear / view:clear
  • 监控与压测:
    • 接入 Laravel Telescope/Debugbar、New Relic/Datadog 定位瓶颈
    • 使用 ab/wrk/k6 逐步调优 workers/task_workers、max_requests、连接与超时,观察 P95/P99 延迟与错误率后再上线。

0