今天我們來安裝和測試一下php的多併發高性能網路通信擴展,這個擴展是使用C語音開發的,載入到PHP以後,在PHP的層面上實現了多併發非同步通信,模擬了go語音的很多特性,極大的拓寬了PHP的應用場景。 直接使用官網上的那句命令就可以,安裝swoole時可能會出現錯誤和卡住不動,多試幾次就能成功。pec ...
今天我們來安裝和測試一下php的多併發高性能網路通信擴展,這個擴展是使用C語音開發的,載入到PHP以後,在PHP的層面上實現了多併發非同步通信,模擬了go語音的很多特性,極大的拓寬了PHP的應用場景。
直接使用官網上的那句命令就可以,安裝swoole時可能會出現錯誤和卡住不動,多試幾次就能成功。
pecl install swoole
要配置php的cli環境和fpm環境的ini文件,把擴展的so載入進去。
視頻地址:
https://www.bilibili.com/video/av70354024/
httpServer.php
$http = new swoole_http_server("127.0.0.1", 9501); $http->on("start", function ($server) { echo "Swoole http server is started at http://127.0.0.1:9501\n"; }); $http->on("request", function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello World\n"); }); $http->start();
註意使用httpClient的時候會有一些錯誤,首先新版的swoole移除了Swoole\Http\Client,會報類找不到,其次要在協程中執行get方法
httpClient.php
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); $client->on("connect", function($cli) { $cli->send("hello world\n"); }); $client->on("receive", function($cli, $data){ echo "received: {$data}\n"; }); $client->on("error", function($cli){ echo "connect failed\n"; }); $client->on("close", function($cli){ echo "connection close\n"; }); $client->connect("127.0.0.1", 9502, 0.5);
taskServer.php
<?php $serv = new Swoole\Server("127.0.0.1", 9502, SWOOLE_BASE); $serv->set(array( 'worker_num' => 2, 'task_worker_num' => 4, )); $serv->on('Receive', function(Swoole\Server $serv, $fd, $from_id, $data) { echo "接收數據" . $data . "\n"; $data = trim($data); $task_id = $serv->task($data, 0); $serv->send($fd, "分發任務,任務id為$task_id\n"); }); $serv->on('Task', function (Swoole\Server $serv, $task_id, $from_id, $data) { echo "Tasker進程接收到數據"; echo "#{$serv->worker_id}\tonTask: [PID={$serv->worker_pid}]: task_id=$task_id, data_len=".strlen($data).".".PHP_EOL; $serv->finish($data); }); $serv->on('Finish', function (Swoole\Server $serv, $task_id, $data) { echo "Task#$task_id finished, data_len=".strlen($data).PHP_EOL; }); $serv->on('workerStart', function($serv, $worker_id) { global $argv; if($worker_id >= $serv->setting['worker_num']) { swoole_set_process_name("php {$argv[0]}: task_worker"); } else { swoole_set_process_name("php {$argv[0]}: worker"); } }); $serv->start();
taskClient.php
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); $client->on("connect", function($cli) { $cli->send("hello world\n"); }); $client->on("receive", function($cli, $data){ echo "received: {$data}\n"; }); $client->on("error", function($cli){ echo "connect failed\n"; }); $client->on("close", function($cli){ echo "connection close\n"; }); $client->connect("127.0.0.1", 9502, 0.5);