Skip to content

Instantly share code, notes, and snippets.

@lotharthesavior
Created May 20, 2022 02:22
Show Gist options
  • Save lotharthesavior/fae997dc9a64e94bea850c03aaa54fe7 to your computer and use it in GitHub Desktop.
Save lotharthesavior/fae997dc9a64e94bea850c03aaa54fe7 to your computer and use it in GitHub Desktop.
OpenSwoole Timer syncing multiple workers data
<?php
Co\run(function() {
go(function () {
var_dump(file_get_contents('http://localhost:9502/requestA'));
});
go(function () {
var_dump(file_get_contents('http://localhost:9502/requestB'));
});
});
<?php
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Timer;
$server = new Server("0.0.0.0", 9502, SWOOLE_PROCESS);
$server->set([
'worker_num' => 4,
]);
$server->on("Start", function(Server $server) {
echo "Swoole Http Server is started at http://127.0.0.1:9502\n";
});
if (!defined('PROCEDURE_KEY')) {
define('PROCEDURE_KEY', 'procedure-key');
}
$table = new Swoole\Table(1024);
$table->column('procedureA', Swoole\Table::TYPE_INT, 1);
$table->column('procedureB', Swoole\Table::TYPE_INT, 1);
$table->column('data', Swoole\Table::TYPE_STRING, 250);
$table->create();
// prepare initial data state
$table->set(PROCEDURE_KEY, ['procedureA' => 0, 'procedureB' => 0, 'data' => '']);
$server->on('Request', function(Request $request, Response $response) use (&$table, $server) {
switch ($request->server['request_uri']) {
case '/requestA':
$data = $table->get(PROCEDURE_KEY);
$data['procedureA'] = 1;
$data['data'] = json_encode(['key' => 'value']);
$table->set(PROCEDURE_KEY, $data);
echo 'pendingProcedureA (worker ' . $server->worker_id . '): ' . $data['procedureA'] . PHP_EOL;
break;
case '/requestB':
$data = $table->get(PROCEDURE_KEY);
$data['procedureB'] = 1;
$table->set(PROCEDURE_KEY, $data);
echo 'pendingProcedureB (worker ' . $server->worker_id . '): ' . $data['procedureB'] . PHP_EOL;
break;
}
$response->end('Done');
});
Timer::tick(1000, function() use (&$table) {
$data = $table->get(PROCEDURE_KEY);
if ($data['procedureA'] === 0 || $data['procedureB'] === 0) {
return;
}
echo "--------------------------------------" . PHP_EOL;
echo json_encode($data) . PHP_EOL;
echo "--------------------------------------" . PHP_EOL;
// reset data
$table->set(PROCEDURE_KEY, ['procedureA' => 0, 'procedureB' => 0, 'data' => '']);
});
$server->start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment