Last active
April 8, 2021 20:19
-
-
Save thbley/3842ef8ff92390ee795dfed77ad39c28 to your computer and use it in GitHub Desktop.
This demo shows how Swoole can handle 100 requests in parallel using 2 php processes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This demo shows how Swoole can handle | |
* 100 requests in parallel using 2 php processes. | |
* | |
* Usage: | |
* php server.php | |
* | |
* To confirm that we only have two worker processes: | |
* ps a | grep swoole | |
* 38947 pts/1 S+ 0:00 php swoole event worker 0 | |
* 38948 pts/1 S+ 0:00 php swoole event worker 1 | |
* | |
* Benchmark to run 100 requests in parallel within 5 seconds: | |
* (each request takes a sleep of 5 seconds) | |
* | |
* siege -c 100 -r 1 -b "http://127.0.0.1:9200/" | |
* ** SIEGE 4.0.4 | |
* ** Preparing 100 concurrent users for battle. | |
* The server is now under siege... | |
* Transactions: 100 hits | |
* Availability: 100.00 % | |
* Elapsed time: 5.02 secs | |
* Data transferred: 0.00 MB | |
* Response time: 5.01 secs | |
* Transaction rate: 19.92 trans/sec | |
* Throughput: 0.00 MB/sec | |
* Concurrency: 99.75 | |
* Successful transactions: 100 | |
* Failed transactions: 0 | |
* Longest transaction: 5.02 | |
* Shortest transaction: 5.00 | |
* | |
* In the output of "php server.php" we will see that all requests happen in parallel: | |
* starting worker 0 | |
* starting worker 1 | |
* 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 | |
* 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 | |
*/ | |
use Swoole\HTTP\Request; | |
use Swoole\HTTP\Response; | |
use Swoole\HTTP\Server; | |
use Swoole\Runtime; | |
error_reporting(E_ALL); | |
ini_set('display_errors', 'On'); | |
Runtime::enableCoroutine(SWOOLE_HOOK_ALL); | |
$http = new Server("0.0.0.0", 9200, SWOOLE_PROCESS, SWOOLE_SOCK_TCP); | |
$http->set([ | |
'worker_num' => 2, // use 2 processes | |
'reactor_num' => 2, // use 2 reactor threads | |
'dispatch_mode' => 1, // 1 = round robin, 2 = fixed mode | |
'log_level' => 4, // warning | |
]); | |
$http->on('WorkerStart', function (Server $server, int $workerId): void { | |
cli_set_process_title('php swoole event worker ' . $workerId); | |
echo 'starting worker ' . $workerId . PHP_EOL; | |
}); | |
$http->on('request', function (Request $request, Response $response) use ($http): void { | |
echo '0'; | |
sleep(5); | |
echo '1'; | |
$response->end('<h1>Hello Swoole.</h1>' . $http->worker_id); | |
}); | |
$http->start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment