1
0
mirror of https://github.com/danog/postgres.git synced 2024-12-02 17:37:57 +01:00
postgres/examples/4-multi-listen.php

66 lines
1.9 KiB
PHP
Raw Normal View History

2017-07-29 17:28:20 +02:00
#!/usr/bin/env php
<?php
2018-07-01 19:33:12 +02:00
require \dirname(__DIR__) . '/vendor/autoload.php';
2017-07-29 17:28:20 +02:00
use Amp\Loop;
use Amp\Postgres;
2020-06-05 16:28:09 +02:00
use Amp\Postgres\Listener;
2020-05-22 07:00:03 +02:00
use Amp\Stream;
2017-07-29 17:28:20 +02:00
Loop::run(function () {
2018-10-15 17:44:40 +02:00
$config = Postgres\ConnectionConfig::fromString('host=localhost user=postgres');
2018-10-14 17:48:07 +02:00
2018-10-15 17:44:40 +02:00
$pool = Postgres\pool($config);
2017-07-29 17:28:20 +02:00
$channel1 = "test1";
$channel2 = "test2";
2020-06-05 16:28:09 +02:00
/** @var Listener $listener1 */
2017-07-29 17:28:20 +02:00
$listener1 = yield $pool->listen($channel1);
2018-07-01 19:33:12 +02:00
\printf("Listening on channel '%s'\n", $listener1->getChannel());
2017-07-29 17:28:20 +02:00
2020-06-05 16:28:09 +02:00
/** @var Listener $listener2 */
2017-07-29 17:28:20 +02:00
$listener2 = yield $pool->listen($channel2);
2018-07-01 19:33:12 +02:00
\printf("Listening on channel '%s'\n", $listener2->getChannel());
2017-07-29 17:28:20 +02:00
Loop::delay(6000, function () use ($listener1) { // Unlisten in 6 seconds.
2018-07-01 19:33:12 +02:00
\printf("Unlistening from channel '%s'\n", $listener1->getChannel());
2017-07-29 17:28:20 +02:00
return $listener1->unlisten();
});
Loop::delay(4000, function () use ($listener2) { // Unlisten in 4 seconds.
2018-07-01 19:33:12 +02:00
\printf("Unlistening from channel '%s'\n", $listener2->getChannel());
2017-07-29 17:28:20 +02:00
return $listener2->unlisten();
});
Loop::delay(1000, function () use ($pool, $channel1) {
return $pool->notify($channel1, "Data 1.1");
});
Loop::delay(2000, function () use ($pool, $channel2) {
return $pool->notify($channel2, "Data 2.1");
});
Loop::delay(3000, function () use ($pool, $channel2) {
return $pool->notify($channel2, "Data 2.2");
});
Loop::delay(5000, function () use ($pool, $channel1) {
return $pool->notify($channel1, "Data 1.2");
});
2020-05-22 07:00:03 +02:00
$stream = Stream\merge([$listener1, $listener2]); // Merge both listeners into single iterator.
2017-07-29 17:28:20 +02:00
2020-05-22 07:00:03 +02:00
while ($notification = yield $stream->continue()) {
2018-07-01 19:33:12 +02:00
\printf(
2017-07-29 17:28:20 +02:00
"Received notification from PID %d on channel '%s' with payload: %s\n",
$notification->pid,
$notification->channel,
$notification->payload
);
}
});