swoole-1.7.7增加了內置Http服務器的支持,通過幾行代碼即可寫出一個異步非阻塞多進程的Http服務器。
常見使用場景:因為swoole是在cli命令下執(zhí)行的,在傳統(tǒng)通過nginx+fastcgi模式下很多root的shell無法執(zhí)行,而使用這個swoole服務器就很好的控制rsync,git,svn等。
$http = new swoole_http_server("127.0.0.1", 9501);
$http->on('request', function ($request, $response) {
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
swoole_http_server對Http協(xié)議的支持并不完整,建議僅作為應用服務器。并且在前端增加Nginx作為代理
$serv = new Swoole\Http\Server("127.0.0.1", 9502);
$serv->on('Request', function($request, $response) {
var_dump($request->get);
var_dump($request->post);
var_dump($request->cookie);
var_dump($request->files);
var_dump($request->header);
var_dump($request->server);
$response->cookie("User", "Swoole");
$response->header("X-Server", "Swoole");
$response->end("<h1>Hello Swoole!</h1>");
});
$serv->start();
通過使用apache bench工具進行壓力測試,在Inter Core-I5 4核 + 8G內存的普通PC機器上,swoole_http_server可以達到近11萬QPS。遠遠超過php-fpm,golang自帶http服務器,node.js自帶http服務器。性能幾乎接近與Nginx的靜態(tài)文件處理。
ab -c 200 -n 200000 -k http://127.0.0.1:9501
nghttp2
庫,下載nghttp2后編譯安裝Http2
協(xié)議必須開啟openssl
openssl
必須支持TLS1.2
、ALPN
、NPN
./configure --enable-openssl --enable-http2
設置http服務器的open_http2_protocol
為true
$serv->set([
'ssl_cert_file' => $ssl_dir . '/ssl.crt',
'ssl_key_file' => $ssl_dir . '/ssl.key',
'open_http2_protocol' => true,
]);
server { root /data/wwwroot/; server_name local.swoole.com; location / { if (!-e $request_filename) { proxy_pass http://127.0.0.1:9501; proxy_http_version 1.1; proxy_set_header Connection "keep-alive"; } } }
Swoole-1.8.0版本增加了對異步Http/WebSocket客戶端的支持。底層是用純C編寫,擁有超高的性能。
異步HTTP客戶端目前仍在實驗階段,請謹慎使用
function swoole_http_client->__construct(string $ip, int port, bool $ssl = false);
更多建議: