SWOOLE OVERVIEW
SWOOLE OVERVIEW
MANUEL
MANUEL
BALDASSARRI
BALDASSARRI
AKA KEA
AKA KEA
@K3A
@K3A
HISTORY AND THEORY
HISTORY AND THEORY
CUMPUTER MULTITASKING
CUMPUTER MULTITASKING
Multiprogramming
Cooperative multitasking
Preemptive multitasking
EVENT LOOP LIBRARIES
EVENT LOOP LIBRARIES
libEvent
libEv
libUv
LOW LEVEL LIBRARIES
LOW LEVEL LIBRARIES
epoll
kqueue
event ports
IOCP
SWOOLE
SWOOLE
https://www.youtube.com/watch?v=WugoE2T3jsw
SWOOLE
SWOOLE
Estensione per PHP
$ pecl install swoole
MAIN FEATURES
MAIN FEATURES
Event-driven, Coroutine, asynchronous programming for PHP
Async TCP / UDP / HTTP / Websocket / HTTP2 client/server side API
IPv4 / IPv6 / Unixsocket / TCP / UDP and SSL / TLS
Fast serializer / unserializer
Milliseconds task scheduler
Daemonize
High performance, scalable, support C1000K
SO WHAT DO WE DO?
SO WHAT DO WE DO?
Chat/Webchat/bot
MQTT Broker
Push notification system
Web monitor system
Speedup laravel/symfony/lumen/slim/yii
Cron task scheduler
Backend for frontend
PHP-FPM client and Proxy
Web crawler
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
$http->on('request', function ($request, $response) {
3
$response->header("Content-Type", "text/plain");
4
$response->end("Hello Worldn");
5
});
6
7
$http->start();
8
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
$http->on('request', function ($request, $response) {
3
$response->header("Content-Type", "text/plain");
4
$response->end("Hello Worldn");
5
});
6
7
$http->start();
8
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello Worldn");
});
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
3
4
5
6
7
$http->start();
8
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
$http->on('request', function ($request, $response) {
3
$response->header("Content-Type", "text/plain");
4
$response->end("Hello Worldn");
5
});
6
7
$http->start();
8
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello Worldn");
});
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
3
4
5
6
7
$http->start();
8 $http->start();
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
$http->on('request', function ($request, $response) {
3
$response->header("Content-Type", "text/plain");
4
$response->end("Hello Worldn");
5
});
6
7
8
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
$http->on('request', function ($request, $response) {
3
$response->header("Content-Type", "text/plain");
4
$response->end("Hello Worldn");
5
});
6
7
$http->start();
8
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello Worldn");
});
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
3
4
5
6
7
$http->start();
8 $http->start();
$http = new SwooleHttpServer("0.0.0.0", 9501);
1
2
$http->on('request', function ($request, $response) {
3
$response->header("Content-Type", "text/plain");
4
$response->end("Hello Worldn");
5
});
6
7
8
$ php my_hello_world_server.php
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
class ServerResponse
{
public function __invoke($request, $response)
{
$response->header('Content-Type', 'text/plain');
$response->end("Hello Worldn");
}
}
$http = new SwooleHttpServer("0.0.0.0", 9501);
$http->on('request', new ServerResponse());
$http->start();
1
2
3
4
5
6
7
8
9
10
11
12
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
class ServerResponse
{
public function theResponsePlease($request, $response)
{
$response->header('Content-Type', 'text/plain');
$response->end("Hello Worldn");
}
}
$http = new SwooleHttpServer("0.0.0.0", 9501);
$http->on('request', [new ServerResponse, 'theResponsePlease']);
$http->start();
HOW IT WORKS
HOW IT WORKS
PROCESSES
PROCESSES
DAEMONIZE
DAEMONIZE
$http = new SwooleHttpServer("0.0.0.0", 9501);
$http->set([
'daemonize' => true,
'log_file' => '/tmp/swoole.log',
]);
$http->on('request', function ($request, $response) {
$response->end("Hello Worldn");
});
$http->start();
1
2
3
4
5
6
7
8
9
10
11
12
DAEMONIZE
DAEMONIZE
$http = new SwooleHttpServer("0.0.0.0", 9501);
$http->set([
'daemonize' => true,
'log_file' => '/tmp/swoole.log',
]);
$http->on('request', function ($request, $response) {
$response->end("Hello Worldn");
});
$http->start();
1
2
3
4
5
6
7
8
9
10
11
12
$ php my_hello_world_server.php
$
HTTPS
HTTPS
$http = new SwooleHttpServer("0.0.0.0", 9501);
$http->set([
'ssl_cert_file' => __DIR__ . '/config/ssl.cert',
'ssl_key_file' => __DIR__ . '/config/ssl.key',
'ssl_ciphers' => 'ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP',
'ssl_method' => SWOOLE_SSLv3_CLIENT_METHOD,
]);
$http->on('request', function ($request, $response) {
$response->end("Hello Worldn");
});
$http->start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
SERVER
SERVER
$server = new SwooleServer("127.0.0.1", 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);
$server->on('Connect', [MyServer::class, 'onConnect']);
$server->on('Receive', [MyServer::class, 'onReceive']);
$server->on('Close', [MyServer::class, 'onClose']);
$server->start();
1
2
3
4
5
6
7
WEBSOCKET 1
WEBSOCKET 1
use SwooleWebSocketServer;
use SwooleHttpRequest;
use SwooleWebSocketFrame;
$server = new SwooleWebSocketServer("0.0.0.0", 9502);
$server->on("start", function (Server $server) {
echo "Swoole WebSocket Server is started at http://127.0.0.1:9502n";
});
$server->on('open', function(Server $server, Request $request) {
echo "connection open: {$request->fd}n";
});
$server->on('message', function(Server $server, Frame $frame) {
echo "received message: {$frame->data}n";
$server->push($frame->fd, json_encode(["hello", time()]));
});
$server->on('close', function(Server $server, int $fd) {
echo "connection close: {$fd}n";
});
$server->start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
PHP-FPM CLIENT
PHP-FPM CLIENT
try {
$client = new SwooleCoroutineFastCGIClient('127.0.0.1', 9000);
$request = (new SwooleFastCGIHttpRequest())
->withScriptFilename(__DIR__ . '/greeter.php')
->withMethod('POST')
->withBody(['who' => 'Swoole']);
$response = $client->execute($request);
echo "Result: {$response->getBody()}n";
} catch (SwooleCoroutineFastCGIClientException $exception) {
echo "Error: {$exception->getMessage()}n";
}
1
2
3
4
5
6
7
8
9
10
11
12
PHP-FPM PROXY
PHP-FPM PROXY
use SwooleConstant;
use SwooleCoroutineFastCGIProxy;
use SwooleHttpRequest;
use SwooleHttpResponse;
use SwooleHttpServer;
$documentRoot = '/var/www/html';
$server = new Server('0.0.0.0', 80, SWOOLE_BASE);
$proxy = new Proxy('127.0.0.1:9000', $documentRoot);
$server->on('request', function (Request $request, Response $response) use ($proxy) {
$proxy->pass($request, $response);
});
$server->start();
1
2
3
4
5
6
7
8
9
10
11
12
13
TIMER
TIMER
$id = SwooleTimer::tick(100, function() {
echo " Do something...n";
});
SwooleTimer::after(500, function() use ($id) {
SwooleTimer::clear($id);
echo " Done...n";
});
SwooleTimer::after(1000, function() use ($id) {
if (!SwooleTimer::exists($id)) {
echo " All right!n";
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
TIMER
TIMER
Do something...
Do something...
Do something...
Do something...
Do something...
Done...
All right!
TIMER
TIMER
int SwooleTimer::after(int $after_time_ms, callable $callback [, string[] $param ])
int SwooleTimer::tick(int $interval_ms, callable $callback [, string[] $param ])
bool SwooleTimer::exists(int $timer_id)
mixed SwooleTimer::list()
mixed SwooleTimer::stats()
mixed SwooleTimer::info(int $timer_id)
bool SwooleTimer::clear(int $timer_id)
bool SwooleTimer::clearAll()
COROUTINE
COROUTINE
Coroutines are computer program components
that generalize subroutines for non-preemptive multitasking
by allowing multiple entry points for suspending and resuming execution at certain
locations.
COROUTINE CLIENTS
COROUTINE CLIENTS
TCP/UDP Client
HTTP/HTTP2/WebSocket Client
Redis Client
MySQL Client
PostgreSQL Client
Coroutine Socket
COROUTINE
COROUTINE
Corun(function() {
go(function() {
$client = new CoHttpClient('www.bing.com', 443, true);
$client->get('/');
echo $client->host."n";
$client->close();
}) ;
go(function() {
$client = new CoHttpClient('www.google.com', 443, true);
$client->get('/');
echo $client->host."n";
$client->close();
}) ;
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
COROUTINE
COROUTINE
Corun(function() {
go(function () {
echo "5 ";
co::sleep(3.0);
go(function () {
echo "3";
co::sleep(2.0);
echo "2 ";
});
echo "1 ";
});
echo "0 ";
co::sleep(1.0);
echo "6 ";
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
COROUTINE
COROUTINE
Corun(function() {
go(function () {
echo "5 ";
co::sleep(3.0);
go(function () {
echo "3";
co::sleep(2.0);
echo "2 ";
});
echo "1 ";
});
echo "0 ";
co::sleep(1.0);
echo "6 ";
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
5 0 6 3 1 2
COROUTINE CHANNEL
COROUTINE CHANNEL
use SwooleCoroutine as co;
$chan = new chan(1);
$producer = go(function() use ($chan) {
while(1) {
$time = date('Y-m-d H:i:s', time());
$chan->push($time);
co::sleep(1);
}
});
$consumer = go(function() use ($chan) {
while (1) {
$time = $chan->pop();
echo "$timen";
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
TABLE (KEY-VALUE STORE)
TABLE (KEY-VALUE STORE)
High performance: read/write speed >2 millions per second
Share variables across multiple threads or processes
Store counters in your application
TABLE (KEY-VALUE STORE)
TABLE (KEY-VALUE STORE)
$table = new SwooleTable(1024);
$table->column('id', SwooleTable::TYPE_INT, 4);
$table->column('name', SwooleTable::TYPE_STRING, 64);
$table->create();
$table->set('a', ['id' => 1, 'name' => 'swoole-co-uk']);
$table->set('b', ['id' => 2, 'name' => "swoole-uk"]);
$table->set('hello@swoole.co.uk', ['id' => 3, 'name' => 'swoole']);
var_dump($table->get('a'));
var_dump($table->get('b', 'name'));
foreach($table as $key => $value)
{
var_dump($key, $value);
}
$table->del('a');
var_dump('count ' . $table->count());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
PROCESS
PROCESS
SwooleProcess SwooleProcess::__construct(
callable $function,
bool $redirect_stdin_stdout = FALSE,
int $create_pipe = 2
);
1
2
3
4
5
$process = new SwooleProcess(function(SwooleProcess $process){
echo "The pid of child process is " . $process->pid . "n";
echo "The FD of pipe is " . $process->pipe . "n";
$process->write("hello");
}, TRUE);
$process->start();
1
2
3
4
5
6
7
8
PROCESS 1
PROCESS 1
$workers = []; $worker_num = 3;
function process(SwooleProcess $process)
{
sleep(rand(5, 10));
$process->write($process->pid);
echo $process->pid."n";
}
for ($i = 0; $i < $worker_num; $i++) {
$process = new SwooleProcess('process');
$pid = $process->start();
$workers[$pid] = $process;
echo "create a child process: $pidn";
}
foreach ($workers as $process) {
swoole_event_add(
$process->pipe,
function ($pipe) use ($process) {
$data = $process->read();
echo "RECV: ".$data."n";
}
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
PROCESS 2
PROCESS 2
$workers = []; $worker_num = 3;
function process(SwooleProcess $process)
{
sleep(rand(5, 10));
$process->write($process->pid);
echo $process->pid."n";
}
for ($i = 0; $i < $worker_num; $i++) {
$process = new SwooleProcess('process');
$pid = $process->start();
$workers[$pid] = $process;
echo "create a child process: $pidn";
}
foreach ($workers as $process) {
swoole_event_add(
$process->pipe,
function ($pipe) use ($process) {
$data = $process->read();
echo "RECV: ".$data."n";
swoole_event_del($pipe);
}
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
PERFORMANCE
PERFORMANCE
NGINX + PHP-FPM
NGINX + PHP-FPM
<?php
echo "Hello world!n";
1
2
NODEJS HTTP SERVER
NODEJS HTTP SERVER
var http = require('http');
http.createServer(
function (request, response) {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write('Hello Node World!');
response.end();
}
).listen(8080);
1
2
3
4
5
6
7
8
9
NODEJS HTTP SERVER
NODEJS HTTP SERVER
var http = require('http');
http.createServer(
function (request, response) {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write('Hello Node World!');
response.end();
}
).listen(8080);
1
2
3
4
5
6
7
8
9
$ node my_hello_world_server.js
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
$http = new swoole_http_server("0.0.0.0", 9501);
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello Worldn");
});
$http->start();
1
2
3
4
5
6
7
8
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
$http = new swoole_http_server("0.0.0.0", 9501);
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello Worldn");
});
$http->start();
1
2
3
4
5
6
7
8
$ php my_hello_world_server.php
NGINX + PHP-FPM + DOCKER
NGINX + PHP-FPM + DOCKER
$ wrk -t6 -c400 -d10s http://127.0.0.1:5000/
Running 10s test @ http://127.0.0.1:5000/
6 threads and 400 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 448.91ms 374.62ms 1.99s 86.82%
Req/Sec 74.06 35.92 200.00 70.41%
4385 requests in 10.07s, 826.47KB read
Requests/sec: 435.63
Transfer/sec: 82.11KB
1
2
3
4
5
6
7
8
9
NGINX + PHP-FPM + DOCKER
NGINX + PHP-FPM + DOCKER
$ wrk -t6 -c400 -d10s http://127.0.0.1:5000/
Running 10s test @ http://127.0.0.1:5000/
6 threads and 400 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 448.91ms 374.62ms 1.99s 86.82%
Req/Sec 74.06 35.92 200.00 70.41%
4385 requests in 10.07s, 826.47KB read
Requests/sec: 435.63
Transfer/sec: 82.11KB
1
2
3
4
5
6
7
8
9
$ wrk -t6 -c400 -d10s http://127.0.0.1:5000/
1
Running 10s test @ http://127.0.0.1:5000/
2
6 threads and 400 connections
3
Thread Stats Avg Stdev Max +/- Stdev
4
Latency 448.91ms 374.62ms 1.99s 86.82%
5
Req/Sec 74.06 35.92 200.00 70.41%
6
4385 requests in 10.07s, 826.47KB read
7
Requests/sec: 435.63
8
Transfer/sec: 82.11KB
9
NGINX + PHP-FPM + DOCKER
NGINX + PHP-FPM + DOCKER
$ wrk -t6 -c400 -d10s http://127.0.0.1:5000/
Running 10s test @ http://127.0.0.1:5000/
6 threads and 400 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 448.91ms 374.62ms 1.99s 86.82%
Req/Sec 74.06 35.92 200.00 70.41%
4385 requests in 10.07s, 826.47KB read
Requests/sec: 435.63
Transfer/sec: 82.11KB
1
2
3
4
5
6
7
8
9
$ wrk -t6 -c400 -d10s http://127.0.0.1:5000/
1
Running 10s test @ http://127.0.0.1:5000/
2
6 threads and 400 connections
3
Thread Stats Avg Stdev Max +/- Stdev
4
Latency 448.91ms 374.62ms 1.99s 86.82%
5
Req/Sec 74.06 35.92 200.00 70.41%
6
4385 requests in 10.07s, 826.47KB read
7
Requests/sec: 435.63
8
Transfer/sec: 82.11KB
9
Thread Stats Avg Stdev Max +/- Stdev
Latency 448.91ms 374.62ms 1.99s 86.82%
Requests/sec: 435.63
$ wrk -t6 -c400 -d10s http://127.0.0.1:5000/
1
Running 10s test @ http://127.0.0.1:5000/
2
6 threads and 400 connections
3
4
5
Req/Sec 74.06 35.92 200.00 70.41%
6
4385 requests in 10.07s, 826.47KB read
7
8
Transfer/sec: 82.11KB
9
NODEJS HTTP SERVER + DOCKER
NODEJS HTTP SERVER + DOCKER
Latency 71.89ms 145.55ms 1.26s 94.30%
Requests/sec: 5298.68
wrk -t6 -c400 -d10s http://127.0.0.1:8081/
1
Running 10s test @ http://127.0.0.1:8081/
2
6 threads and 400 connections
3
Thread Stats Avg Stdev Max +/- Stdev
4
5
Req/Sec 0.96k 550.60 2.54k 61.50%
6
53227 requests in 10.05s, 8.22MB read
7
8
Transfer/sec: 838.27KB
9
SWOOLE HTTP SERVER + DOCKER
SWOOLE HTTP SERVER + DOCKER
Latency 21.19ms 21.70ms 291.39ms 96.42%
Requests/sec: 12276.27
wrk -t6 -c400 -d10s http://127.0.0.1:9501/
1
Running 10s test @ http://127.0.0.1:9501/
2
6 threads and 400 connections
3
Thread Stats Avg Stdev Max +/- Stdev
4
5
Req/Sec 2.08k 811.38 3.81k 60.27%
6
122950 requests in 10.02s, 19.46MB read
7
8
Transfer/sec: 1.94MB
9
NODEJS HTTP SERVER
NODEJS HTTP SERVER
Latency 6.44ms 1.09ms 25.93ms 93.61%
Requests/sec: 38327.35
$ wrk -t6 -c400 -d10s http://127.0.0.1:8080/
1
Running 10s test @ http://127.0.0.1:8080/
2
6 threads and 400 connections
3
Thread Stats Avg Stdev Max +/- Stdev
4
5
Req/Sec 6.42k 1.66k 9.42k 60.07%
6
387213 requests in 10.10s, 59.82MB read
7
8
Transfer/sec: 5.92MB
9
SWOOLE HTTP SERVER
SWOOLE HTTP SERVER
Latency 2.22ms 270.95us 15.03ms 89.53%
Requests/sec: 109699.00
$ wrk -t6 -c400 -d10s http://127.0.0.1:9501/
1
Running 10s test @ http://127.0.0.1:9501/
2
6 threads and 400 connections
3
Thread Stats Avg Stdev Max +/- Stdev
4
5
Req/Sec 18.44k 3.65k 35.10k 74.50%
6
1108296 requests in 10.10s, 175.45MB read
7
8
Transfer/sec: 17.37MB
9
"HELLO WORLD" BENCHMARK
"HELLO WORLD" BENCHMARK
2.9 GHz, i7 quad-core, 16GB Ram
TECHEMPOWER BENCHMARKS
TECHEMPOWER BENCHMARKS
[07/19]
https://www.techempower.com/benchmarks/
PRODUCTION READY?
PRODUCTION READY?
PRODUCTION READY?
PRODUCTION READY?
Tencent
microservices, long-time connection
Baidu
high-performance app, performance data collection services, peak period 500,000 qps
JD.com
WebAPI, WebSocket
2345
real-time data push of PC-side, users online more than 10 million
"Legend of Sword"
RPG role-playing game server
CONS
CONS
Documentazione ufficiale delle API poco approfondita
Mancanza di esempi di applicazioni complesse
La stragrande maggioranze di documenti/case/video è in
Il workspace slack di Swoole ha ~300 membri (GrUSP ~1500)
LINKS
LINKS
https://www.swoole.co.uk/ [en]
https://www.swoole.com/ [cn]
https://speakerdeck.com/doubaokun/coroutine-based-concurrency-with-php-and-swoole
https://corun.io/
https://github.com/swooletw/awesome-swoole
THANK YOU!
THANK YOU!

Swoole Overview

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
    EVENT LOOP LIBRARIES EVENTLOOP LIBRARIES libEvent libEv libUv
  • 6.
    LOW LEVEL LIBRARIES LOWLEVEL LIBRARIES epoll kqueue event ports IOCP
  • 8.
  • 9.
  • 10.
    MAIN FEATURES MAIN FEATURES Event-driven,Coroutine, asynchronous programming for PHP Async TCP / UDP / HTTP / Websocket / HTTP2 client/server side API IPv4 / IPv6 / Unixsocket / TCP / UDP and SSL / TLS Fast serializer / unserializer Milliseconds task scheduler Daemonize High performance, scalable, support C1000K
  • 12.
    SO WHAT DOWE DO? SO WHAT DO WE DO? Chat/Webchat/bot MQTT Broker Push notification system Web monitor system Speedup laravel/symfony/lumen/slim/yii Cron task scheduler Backend for frontend PHP-FPM client and Proxy Web crawler
  • 14.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 $http->on('request', function ($request, $response) { 3 $response->header("Content-Type", "text/plain"); 4 $response->end("Hello Worldn"); 5 }); 6 7 $http->start(); 8
  • 15.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 $http->on('request', function ($request, $response) { 3 $response->header("Content-Type", "text/plain"); 4 $response->end("Hello Worldn"); 5 }); 6 7 $http->start(); 8 $http->on('request', function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello Worldn"); }); $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 3 4 5 6 7 $http->start(); 8
  • 16.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 $http->on('request', function ($request, $response) { 3 $response->header("Content-Type", "text/plain"); 4 $response->end("Hello Worldn"); 5 }); 6 7 $http->start(); 8 $http->on('request', function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello Worldn"); }); $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 3 4 5 6 7 $http->start(); 8 $http->start(); $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 $http->on('request', function ($request, $response) { 3 $response->header("Content-Type", "text/plain"); 4 $response->end("Hello Worldn"); 5 }); 6 7 8
  • 17.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 $http->on('request', function ($request, $response) { 3 $response->header("Content-Type", "text/plain"); 4 $response->end("Hello Worldn"); 5 }); 6 7 $http->start(); 8 $http->on('request', function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello Worldn"); }); $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 3 4 5 6 7 $http->start(); 8 $http->start(); $http = new SwooleHttpServer("0.0.0.0", 9501); 1 2 $http->on('request', function ($request, $response) { 3 $response->header("Content-Type", "text/plain"); 4 $response->end("Hello Worldn"); 5 }); 6 7 8 $ php my_hello_world_server.php
  • 18.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER class ServerResponse { public function __invoke($request, $response) { $response->header('Content-Type', 'text/plain'); $response->end("Hello Worldn"); } } $http = new SwooleHttpServer("0.0.0.0", 9501); $http->on('request', new ServerResponse()); $http->start(); 1 2 3 4 5 6 7 8 9 10 11 12
  • 19.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER class ServerResponse { public function theResponsePlease($request, $response) { $response->header('Content-Type', 'text/plain'); $response->end("Hello Worldn"); } } $http = new SwooleHttpServer("0.0.0.0", 9501); $http->on('request', [new ServerResponse, 'theResponsePlease']); $http->start();
  • 20.
  • 21.
  • 22.
    DAEMONIZE DAEMONIZE $http = newSwooleHttpServer("0.0.0.0", 9501); $http->set([ 'daemonize' => true, 'log_file' => '/tmp/swoole.log', ]); $http->on('request', function ($request, $response) { $response->end("Hello Worldn"); }); $http->start(); 1 2 3 4 5 6 7 8 9 10 11 12
  • 23.
    DAEMONIZE DAEMONIZE $http = newSwooleHttpServer("0.0.0.0", 9501); $http->set([ 'daemonize' => true, 'log_file' => '/tmp/swoole.log', ]); $http->on('request', function ($request, $response) { $response->end("Hello Worldn"); }); $http->start(); 1 2 3 4 5 6 7 8 9 10 11 12 $ php my_hello_world_server.php $
  • 24.
    HTTPS HTTPS $http = newSwooleHttpServer("0.0.0.0", 9501); $http->set([ 'ssl_cert_file' => __DIR__ . '/config/ssl.cert', 'ssl_key_file' => __DIR__ . '/config/ssl.key', 'ssl_ciphers' => 'ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP', 'ssl_method' => SWOOLE_SSLv3_CLIENT_METHOD, ]); $http->on('request', function ($request, $response) { $response->end("Hello Worldn"); }); $http->start(); 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 25.
    SERVER SERVER $server = newSwooleServer("127.0.0.1", 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP); $server->on('Connect', [MyServer::class, 'onConnect']); $server->on('Receive', [MyServer::class, 'onReceive']); $server->on('Close', [MyServer::class, 'onClose']); $server->start(); 1 2 3 4 5 6 7
  • 26.
    WEBSOCKET 1 WEBSOCKET 1 useSwooleWebSocketServer; use SwooleHttpRequest; use SwooleWebSocketFrame; $server = new SwooleWebSocketServer("0.0.0.0", 9502); $server->on("start", function (Server $server) { echo "Swoole WebSocket Server is started at http://127.0.0.1:9502n"; }); $server->on('open', function(Server $server, Request $request) { echo "connection open: {$request->fd}n"; }); $server->on('message', function(Server $server, Frame $frame) { echo "received message: {$frame->data}n"; $server->push($frame->fd, json_encode(["hello", time()])); }); $server->on('close', function(Server $server, int $fd) { echo "connection close: {$fd}n"; }); $server->start(); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
  • 27.
    PHP-FPM CLIENT PHP-FPM CLIENT try{ $client = new SwooleCoroutineFastCGIClient('127.0.0.1', 9000); $request = (new SwooleFastCGIHttpRequest()) ->withScriptFilename(__DIR__ . '/greeter.php') ->withMethod('POST') ->withBody(['who' => 'Swoole']); $response = $client->execute($request); echo "Result: {$response->getBody()}n"; } catch (SwooleCoroutineFastCGIClientException $exception) { echo "Error: {$exception->getMessage()}n"; } 1 2 3 4 5 6 7 8 9 10 11 12
  • 28.
    PHP-FPM PROXY PHP-FPM PROXY useSwooleConstant; use SwooleCoroutineFastCGIProxy; use SwooleHttpRequest; use SwooleHttpResponse; use SwooleHttpServer; $documentRoot = '/var/www/html'; $server = new Server('0.0.0.0', 80, SWOOLE_BASE); $proxy = new Proxy('127.0.0.1:9000', $documentRoot); $server->on('request', function (Request $request, Response $response) use ($proxy) { $proxy->pass($request, $response); }); $server->start(); 1 2 3 4 5 6 7 8 9 10 11 12 13
  • 29.
    TIMER TIMER $id = SwooleTimer::tick(100,function() { echo " Do something...n"; }); SwooleTimer::after(500, function() use ($id) { SwooleTimer::clear($id); echo " Done...n"; }); SwooleTimer::after(1000, function() use ($id) { if (!SwooleTimer::exists($id)) { echo " All right!n"; } }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 30.
    TIMER TIMER Do something... Do something... Dosomething... Do something... Do something... Done... All right!
  • 31.
    TIMER TIMER int SwooleTimer::after(int $after_time_ms,callable $callback [, string[] $param ]) int SwooleTimer::tick(int $interval_ms, callable $callback [, string[] $param ]) bool SwooleTimer::exists(int $timer_id) mixed SwooleTimer::list() mixed SwooleTimer::stats() mixed SwooleTimer::info(int $timer_id) bool SwooleTimer::clear(int $timer_id) bool SwooleTimer::clearAll()
  • 32.
    COROUTINE COROUTINE Coroutines are computerprogram components that generalize subroutines for non-preemptive multitasking by allowing multiple entry points for suspending and resuming execution at certain locations.
  • 33.
    COROUTINE CLIENTS COROUTINE CLIENTS TCP/UDPClient HTTP/HTTP2/WebSocket Client Redis Client MySQL Client PostgreSQL Client Coroutine Socket
  • 34.
    COROUTINE COROUTINE Corun(function() { go(function() { $client= new CoHttpClient('www.bing.com', 443, true); $client->get('/'); echo $client->host."n"; $client->close(); }) ; go(function() { $client = new CoHttpClient('www.google.com', 443, true); $client->get('/'); echo $client->host."n"; $client->close(); }) ; }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 35.
    COROUTINE COROUTINE Corun(function() { go(function (){ echo "5 "; co::sleep(3.0); go(function () { echo "3"; co::sleep(2.0); echo "2 "; }); echo "1 "; }); echo "0 "; co::sleep(1.0); echo "6 "; }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  • 36.
    COROUTINE COROUTINE Corun(function() { go(function (){ echo "5 "; co::sleep(3.0); go(function () { echo "3"; co::sleep(2.0); echo "2 "; }); echo "1 "; }); echo "0 "; co::sleep(1.0); echo "6 "; }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 5 0 6 3 1 2
  • 37.
    COROUTINE CHANNEL COROUTINE CHANNEL useSwooleCoroutine as co; $chan = new chan(1); $producer = go(function() use ($chan) { while(1) { $time = date('Y-m-d H:i:s', time()); $chan->push($time); co::sleep(1); } }); $consumer = go(function() use ($chan) { while (1) { $time = $chan->pop(); echo "$timen"; } }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
  • 38.
    TABLE (KEY-VALUE STORE) TABLE(KEY-VALUE STORE) High performance: read/write speed >2 millions per second Share variables across multiple threads or processes Store counters in your application
  • 39.
    TABLE (KEY-VALUE STORE) TABLE(KEY-VALUE STORE) $table = new SwooleTable(1024); $table->column('id', SwooleTable::TYPE_INT, 4); $table->column('name', SwooleTable::TYPE_STRING, 64); $table->create(); $table->set('a', ['id' => 1, 'name' => 'swoole-co-uk']); $table->set('b', ['id' => 2, 'name' => "swoole-uk"]); $table->set('hello@swoole.co.uk', ['id' => 3, 'name' => 'swoole']); var_dump($table->get('a')); var_dump($table->get('b', 'name')); foreach($table as $key => $value) { var_dump($key, $value); } $table->del('a'); var_dump('count ' . $table->count()); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
  • 40.
    PROCESS PROCESS SwooleProcess SwooleProcess::__construct( callable $function, bool$redirect_stdin_stdout = FALSE, int $create_pipe = 2 ); 1 2 3 4 5 $process = new SwooleProcess(function(SwooleProcess $process){ echo "The pid of child process is " . $process->pid . "n"; echo "The FD of pipe is " . $process->pipe . "n"; $process->write("hello"); }, TRUE); $process->start(); 1 2 3 4 5 6 7 8
  • 41.
    PROCESS 1 PROCESS 1 $workers= []; $worker_num = 3; function process(SwooleProcess $process) { sleep(rand(5, 10)); $process->write($process->pid); echo $process->pid."n"; } for ($i = 0; $i < $worker_num; $i++) { $process = new SwooleProcess('process'); $pid = $process->start(); $workers[$pid] = $process; echo "create a child process: $pidn"; } foreach ($workers as $process) { swoole_event_add( $process->pipe, function ($pipe) use ($process) { $data = $process->read(); echo "RECV: ".$data."n"; } ); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  • 42.
    PROCESS 2 PROCESS 2 $workers= []; $worker_num = 3; function process(SwooleProcess $process) { sleep(rand(5, 10)); $process->write($process->pid); echo $process->pid."n"; } for ($i = 0; $i < $worker_num; $i++) { $process = new SwooleProcess('process'); $pid = $process->start(); $workers[$pid] = $process; echo "create a child process: $pidn"; } foreach ($workers as $process) { swoole_event_add( $process->pipe, function ($pipe) use ($process) { $data = $process->read(); echo "RECV: ".$data."n"; swoole_event_del($pipe); } ); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
  • 43.
  • 44.
    NGINX + PHP-FPM NGINX+ PHP-FPM <?php echo "Hello world!n"; 1 2
  • 45.
    NODEJS HTTP SERVER NODEJSHTTP SERVER var http = require('http'); http.createServer( function (request, response) { response.writeHead(200, { 'Content-Type': 'text/plain' }); response.write('Hello Node World!'); response.end(); } ).listen(8080); 1 2 3 4 5 6 7 8 9
  • 46.
    NODEJS HTTP SERVER NODEJSHTTP SERVER var http = require('http'); http.createServer( function (request, response) { response.writeHead(200, { 'Content-Type': 'text/plain' }); response.write('Hello Node World!'); response.end(); } ).listen(8080); 1 2 3 4 5 6 7 8 9 $ node my_hello_world_server.js
  • 47.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER $http = new swoole_http_server("0.0.0.0", 9501); $http->on('request', function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello Worldn"); }); $http->start(); 1 2 3 4 5 6 7 8
  • 48.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER $http = new swoole_http_server("0.0.0.0", 9501); $http->on('request', function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello Worldn"); }); $http->start(); 1 2 3 4 5 6 7 8 $ php my_hello_world_server.php
  • 49.
    NGINX + PHP-FPM+ DOCKER NGINX + PHP-FPM + DOCKER $ wrk -t6 -c400 -d10s http://127.0.0.1:5000/ Running 10s test @ http://127.0.0.1:5000/ 6 threads and 400 connections Thread Stats Avg Stdev Max +/- Stdev Latency 448.91ms 374.62ms 1.99s 86.82% Req/Sec 74.06 35.92 200.00 70.41% 4385 requests in 10.07s, 826.47KB read Requests/sec: 435.63 Transfer/sec: 82.11KB 1 2 3 4 5 6 7 8 9
  • 50.
    NGINX + PHP-FPM+ DOCKER NGINX + PHP-FPM + DOCKER $ wrk -t6 -c400 -d10s http://127.0.0.1:5000/ Running 10s test @ http://127.0.0.1:5000/ 6 threads and 400 connections Thread Stats Avg Stdev Max +/- Stdev Latency 448.91ms 374.62ms 1.99s 86.82% Req/Sec 74.06 35.92 200.00 70.41% 4385 requests in 10.07s, 826.47KB read Requests/sec: 435.63 Transfer/sec: 82.11KB 1 2 3 4 5 6 7 8 9 $ wrk -t6 -c400 -d10s http://127.0.0.1:5000/ 1 Running 10s test @ http://127.0.0.1:5000/ 2 6 threads and 400 connections 3 Thread Stats Avg Stdev Max +/- Stdev 4 Latency 448.91ms 374.62ms 1.99s 86.82% 5 Req/Sec 74.06 35.92 200.00 70.41% 6 4385 requests in 10.07s, 826.47KB read 7 Requests/sec: 435.63 8 Transfer/sec: 82.11KB 9
  • 51.
    NGINX + PHP-FPM+ DOCKER NGINX + PHP-FPM + DOCKER $ wrk -t6 -c400 -d10s http://127.0.0.1:5000/ Running 10s test @ http://127.0.0.1:5000/ 6 threads and 400 connections Thread Stats Avg Stdev Max +/- Stdev Latency 448.91ms 374.62ms 1.99s 86.82% Req/Sec 74.06 35.92 200.00 70.41% 4385 requests in 10.07s, 826.47KB read Requests/sec: 435.63 Transfer/sec: 82.11KB 1 2 3 4 5 6 7 8 9 $ wrk -t6 -c400 -d10s http://127.0.0.1:5000/ 1 Running 10s test @ http://127.0.0.1:5000/ 2 6 threads and 400 connections 3 Thread Stats Avg Stdev Max +/- Stdev 4 Latency 448.91ms 374.62ms 1.99s 86.82% 5 Req/Sec 74.06 35.92 200.00 70.41% 6 4385 requests in 10.07s, 826.47KB read 7 Requests/sec: 435.63 8 Transfer/sec: 82.11KB 9 Thread Stats Avg Stdev Max +/- Stdev Latency 448.91ms 374.62ms 1.99s 86.82% Requests/sec: 435.63 $ wrk -t6 -c400 -d10s http://127.0.0.1:5000/ 1 Running 10s test @ http://127.0.0.1:5000/ 2 6 threads and 400 connections 3 4 5 Req/Sec 74.06 35.92 200.00 70.41% 6 4385 requests in 10.07s, 826.47KB read 7 8 Transfer/sec: 82.11KB 9
  • 52.
    NODEJS HTTP SERVER+ DOCKER NODEJS HTTP SERVER + DOCKER Latency 71.89ms 145.55ms 1.26s 94.30% Requests/sec: 5298.68 wrk -t6 -c400 -d10s http://127.0.0.1:8081/ 1 Running 10s test @ http://127.0.0.1:8081/ 2 6 threads and 400 connections 3 Thread Stats Avg Stdev Max +/- Stdev 4 5 Req/Sec 0.96k 550.60 2.54k 61.50% 6 53227 requests in 10.05s, 8.22MB read 7 8 Transfer/sec: 838.27KB 9
  • 53.
    SWOOLE HTTP SERVER+ DOCKER SWOOLE HTTP SERVER + DOCKER Latency 21.19ms 21.70ms 291.39ms 96.42% Requests/sec: 12276.27 wrk -t6 -c400 -d10s http://127.0.0.1:9501/ 1 Running 10s test @ http://127.0.0.1:9501/ 2 6 threads and 400 connections 3 Thread Stats Avg Stdev Max +/- Stdev 4 5 Req/Sec 2.08k 811.38 3.81k 60.27% 6 122950 requests in 10.02s, 19.46MB read 7 8 Transfer/sec: 1.94MB 9
  • 54.
    NODEJS HTTP SERVER NODEJSHTTP SERVER Latency 6.44ms 1.09ms 25.93ms 93.61% Requests/sec: 38327.35 $ wrk -t6 -c400 -d10s http://127.0.0.1:8080/ 1 Running 10s test @ http://127.0.0.1:8080/ 2 6 threads and 400 connections 3 Thread Stats Avg Stdev Max +/- Stdev 4 5 Req/Sec 6.42k 1.66k 9.42k 60.07% 6 387213 requests in 10.10s, 59.82MB read 7 8 Transfer/sec: 5.92MB 9
  • 55.
    SWOOLE HTTP SERVER SWOOLEHTTP SERVER Latency 2.22ms 270.95us 15.03ms 89.53% Requests/sec: 109699.00 $ wrk -t6 -c400 -d10s http://127.0.0.1:9501/ 1 Running 10s test @ http://127.0.0.1:9501/ 2 6 threads and 400 connections 3 Thread Stats Avg Stdev Max +/- Stdev 4 5 Req/Sec 18.44k 3.65k 35.10k 74.50% 6 1108296 requests in 10.10s, 175.45MB read 7 8 Transfer/sec: 17.37MB 9
  • 57.
    "HELLO WORLD" BENCHMARK "HELLOWORLD" BENCHMARK 2.9 GHz, i7 quad-core, 16GB Ram
  • 58.
  • 59.
  • 60.
    PRODUCTION READY? PRODUCTION READY? Tencent microservices,long-time connection Baidu high-performance app, performance data collection services, peak period 500,000 qps JD.com WebAPI, WebSocket 2345 real-time data push of PC-side, users online more than 10 million "Legend of Sword" RPG role-playing game server
  • 61.
    CONS CONS Documentazione ufficiale delleAPI poco approfondita Mancanza di esempi di applicazioni complesse La stragrande maggioranze di documenti/case/video è in Il workspace slack di Swoole ha ~300 membri (GrUSP ~1500)
  • 62.
  • 63.