傳統 PHP 執行模型是同步阻塞的,面對高併發場景時效能往往成為瓶頸。Swoole 作為 PHP 的高效能網路通訊框架,透過 C 語言擴展實現了異步非阻塞 I/O、多進程/多線程、協程等特性,讓 PHP 也能輕鬆應對萬級併發。本文將透過實際測試代碼與壓測數據,帶你快速上手 Swoole 的核心用法。
在 Ubuntu 下安裝 Swoole 擴展後,我們編寫一個簡單的控制器進行壓測:
<?php
class Page extends Controller
{
public function index()
{
$data = createModel('UserInfo')->get(12)->get();
$this->swoole->tpl->assign('data', $data);
$html = $this->swoole->tpl->fetch('test.html');
$time = $this->showTime();
return $html . $time;
}
}
使用 ApacheBench (ab) 進行壓測:
ab -c 100 -n 1000 -k https://127.0.0.1/index/
關注三個核心指標:
| 模式 | 單進程 QPS | 單進程 平均耗時(ms) | 4 進程 QPS | 4 進程 平均耗時(ms) |
|---|---|---|---|---|
| Swoole EventTCP | 571.70 | 174.92 | 1153.63 | 86.68 |
| Swoole SelectTCP | 659.01 | 151.74 | 1010.08 | 99.00 |
| Swoole BlockTCP | 561.24 | 178.18 | 1094.58 | 91.36 |
| Apache Prefork | 80.57 | 1241.08 | — | — |
從數據可見,Swoole 在單進程下即遠超傳統 Apache Prefork,開啟多進程後吞吐量更是成倍增長。對於追求高併發、低延遲的 PHP 專案,Swoole 是不二之選。建議開發者深入學習其協程特性,進一步釋放 PHP 的高效能潛力。