SlideShare a Scribd company logo
1 of 63
Download to read offline
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!

More Related Content

Similar to Swoole Overview

The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CDavid Wheeler
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experiencedrajkamaltibacademy
 
REST in AngularJS
REST in AngularJSREST in AngularJS
REST in AngularJSa_sharif
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionAdam Trachtenberg
 
Getting out of Callback Hell in PHP
Getting out of Callback Hell in PHPGetting out of Callback Hell in PHP
Getting out of Callback Hell in PHPArul Kumaran
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Nordic APIs
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)xSawyer
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Jakub Zalas
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perldeepfountainconsulting
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
Frameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHPFrameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHPDan Jesus
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Kacper Gunia
 

Similar to Swoole Overview (20)

The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning C
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
 
REST in AngularJS
REST in AngularJSREST in AngularJS
REST in AngularJS
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP Extension
 
Laravel 101
Laravel 101Laravel 101
Laravel 101
 
Modern php
Modern phpModern php
Modern php
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Getting out of Callback Hell in PHP
Getting out of Callback Hell in PHPGetting out of Callback Hell in PHP
Getting out of Callback Hell in PHP
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Frameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHPFrameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHP
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 

More from Manuel Baldassarri

More from Manuel Baldassarri (8)

Videogiochi in PHP 👾
Videogiochi in PHP 👾Videogiochi in PHP 👾
Videogiochi in PHP 👾
 
From * to Symfony2
From * to Symfony2From * to Symfony2
From * to Symfony2
 
Un CMS in 25min con Symfony CMF
Un CMS in 25min con Symfony CMFUn CMS in 25min con Symfony CMF
Un CMS in 25min con Symfony CMF
 
Automazione quotidiana in php
Automazione quotidiana in phpAutomazione quotidiana in php
Automazione quotidiana in php
 
Symfony2 security layer
Symfony2 security layerSymfony2 security layer
Symfony2 security layer
 
Symfony CMF: un nuovo paradigma per la gestione dei contenuti
Symfony CMF: un nuovo paradigma per la gestione dei contenutiSymfony CMF: un nuovo paradigma per la gestione dei contenuti
Symfony CMF: un nuovo paradigma per la gestione dei contenuti
 
Ant vs Phing
Ant vs PhingAnt vs Phing
Ant vs Phing
 
Form refactoring
Form refactoringForm refactoring
Form refactoring
 

Recently uploaded

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Swoole Overview

  • 5. EVENT LOOP LIBRARIES EVENT LOOP LIBRARIES libEvent libEv libUv
  • 6. LOW LEVEL LIBRARIES LOW LEVEL LIBRARIES epoll kqueue event ports IOCP
  • 7.
  • 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
  • 11.
  • 12. 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
  • 13.
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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();
  • 20. HOW IT WORKS HOW IT WORKS
  • 22. 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
  • 23. 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 $
  • 24. 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
  • 25. 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
  • 26. 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
  • 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 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
  • 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... Do something... 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 computer program 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/UDP Client 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 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
  • 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
  • 44. NGINX + PHP-FPM NGINX + PHP-FPM <?php echo "Hello world!n"; 1 2
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. 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
  • 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 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
  • 55. 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
  • 56.
  • 57. "HELLO WORLD" BENCHMARK "HELLO WORLD" BENCHMARK 2.9 GHz, i7 quad-core, 16GB Ram
  • 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 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)