Question
Swoole\Server::start(): eventLoop has already been created, unable to start Swoole\Http\ServerExample:
# Blocking function to pre-load/refresh some cache in static variables (faster than the table/have the ram).
function cacheData() {
$wg = new Swoole\Coroutine\WaitGroup();
# async IO
go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
# wait for all of them
$wg->wait();
}
...
cacheData(); # Load the data before the server start
$http = new Server($listen_ip, $listen_port);
# Refresh the data inside each worker at a set interval.
$http->on('workerStart', function(Server $server, int $worker_id) {
Timer::tick(1000, function () { cacheData(); });
});
...
$http->start(); # << error: Swoole\Server::start(): eventLoop has already been created, unable to start Swoole\Http\Server
You need to use theSwoole\Coroutine\run method and then use the coroutine inside:
<?php
use Swoole\Http\Server;
use function Swoole\Coroutine\run;
run(function () {
$wg = new Swoole\Coroutine\WaitGroup();
# async IO
go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
# wait for all of them
$wg->wait();
});
$http = new Server("0.0.0.0", 49501);
$http->on('request', function ($request, $response) {
$response->end("<h1>Hello World. #".rand(1000, 9999)."</h1>");
});
$http->start();
Awesome, thank you, makes sense now.
The Chinese documentation (wiki.swoole.com) seems very good and logical, but once passed through google translate, it can lose some info/semantics, so some terms become confusing/not so clear.
Most helpful comment
Awesome, thank you, makes sense now.
The Chinese documentation (wiki.swoole.com) seems very good and logical, but once passed through google translate, it can lose some info/semantics, so some terms become confusing/not so clear.