Swoole HttpServer實例

2019-08-14 19:13 更新

Swoole HttpServer介紹

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


使用Http2協(xié)議

  • 需要依賴nghttp2庫,下載nghttp2后編譯安裝
  • 使用Http2協(xié)議必須開啟openssl
  • 需要高版本openssl必須支持TLS1.2ALPN、NPN
./configure --enable-openssl --enable-http2

設置http服務器的open_http2_protocoltrue

$serv->set([
    'ssl_cert_file' => $ssl_dir . '/ssl.crt',
    'ssl_key_file' => $ssl_dir . '/ssl.key',
    'open_http2_protocol' => true,
]);

nginx+swoole配置

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";
        }
    }
}


異步Http/WebSocket客戶端

Swoole-1.8.0版本增加了對異步Http/WebSocket客戶端的支持。底層是用純C編寫,擁有超高的性能。

異步HTTP客戶端目前仍在實驗階段,請謹慎使用

啟用Http客戶端

  • 1.8.6版本之前,需要在編譯swoole時增加--enable-async-httpclient來開啟此功能。
  • swoole_http_client不依賴任何第三方庫
  • 支持Http-Chunk、Keep-Alive特性,暫不支持form-data格式
  • Http協(xié)議版本為HTTP/1.1
  • gzip壓縮格式支持需要依賴zlib庫

構造方法

function swoole_http_client->__construct(string $ip, int port, bool $ssl = false);
  • $ip 目標服務器的IP地址,可使用swoole_async_dns_lookup查詢域名對應的IP地址
  • $port 目標服務器的端口,一般http為80,https為443
  • $ssl 是否啟用SSL/TLS隧道加密,如果目標服務器是https必須設置$ssl參數(shù)為true


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號