標籤:style http io os ar 使用 for sp strong
PHP的非同步並行swoole擴充在1.7.7中內建了一個Http伺服器,利用swoole_http_server可以輕鬆實現一個PHP的非同步Web伺服器,效能比php-fpm/Apache等同步阻塞的伺服器高出數倍。
swoole官方還提供了redis-async,一個非同步IO+串連池的Redis用戶端。這2個功能結合起來就可以打造一個並發請求數萬的Web應用。
使用方法
1. 下載安裝swoole擴充
可以使用pecl安裝或者從github下載swoole最新的stable版本。
pecl install swoole
修改php.ini加入extension=swoole.so
2、下載redis-async代碼
git clone https://github.com/swoole/redis-async.git
3、編寫伺服器代碼server.php
$http = new swoole_http_server("127.0.0.1", 9501);$http->set([‘worker_num‘ => 8]);require __DIR__.‘/src/Swoole/Async/RedisClient.php‘;$redis = new Swoole\Async\RedisClient(‘127.0.0.1‘);$http->on(‘request‘, function ($request, $response) use ($redis) { $redis->get(‘key1‘, function($result) use($response) { $response->end("<h1>Hello Swoole. value=".$result."</h1>"); });});$http->start();
運行server.php程式,這裡一共啟動了8個進程。注意由於是非同步非阻塞的伺服器程式,所以不需要像Apache/PHP-fpm那樣開啟數百的進程。這裡完全是沒有等待的,全部是事件驅動。當請求到來發起redis請求,redis-server響應後會觸發對應的事件,再渲染頁面,將HTML頁面通過$response->end介面發送給瀏覽器。
php server.php
Http伺服器啟動監聽了9501連接埠,瀏覽器中可以開啟 http://127.0.0.1:9501 訪問頁面。本程式的邏輯很簡單,只是從redis中取一個資料,並渲染頁面。
4、使用ab工具進行壓力測試
ab -c 200 -n 100000 -k http://127.0.0.1:9501/
機器環境是:Inter CoreI5 4核CPU+8G記憶體,Ubuntu 14.04
壓測結果:
Server Software: swoole-http-serverServer Hostname: 127.0.0.1Server Port: 9501Document Path: /Document Length: 40 bytesConcurrency Level: 200Time taken for tests: 2.853 secondsComplete requests: 100000Failed requests: 0Keep-Alive requests: 100000Total transferred: 16800000 bytesHTML transferred: 4000000 bytesRequests per second: 35049.02 [#/sec] (mean)Time per request: 5.706 [ms] (mean)Time per request: 0.029 [ms] (mean, across all concurrent requests)Transfer rate: 5750.23 [Kbytes/sec] received
可以達到3.5萬QPS,效能驚人,僅僅使用一台普通的PC機器,硬體效能一般。如果是在伺服器硬體環境中,效能可以更好。
PHP的非同步Web伺服器+非同步Redis用戶端