-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
subscribe.php
37 lines (28 loc) · 1.22 KB
/
subscribe.php
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
27
28
29
30
31
32
33
34
35
36
37
<?php
// $ php examples/subscribe.php
// $ REDIS_URI=localhost:6379 php examples/subscribe.php channel
use React\EventLoop\Loop;
require __DIR__ . '/../vendor/autoload.php';
$channel = $argv[1] ?? 'channel';
$redis = new Clue\React\Redis\RedisClient(getenv('REDIS_URI') ?: 'localhost:6379');
$redis->subscribe($channel)->then(function () {
echo 'Now subscribed to channel ' . PHP_EOL;
}, function (Exception $e) use ($redis) {
$redis->close();
echo 'Unable to subscribe: ' . $e->getMessage() . PHP_EOL;
});
$redis->on('message', function (string $channel, string $message) {
echo 'Message on ' . $channel . ': ' . $message . PHP_EOL;
});
// automatically re-subscribe to channel on connection issues
$redis->on('unsubscribe', function (string $channel) use ($redis) {
echo 'Unsubscribed from ' . $channel . PHP_EOL;
Loop::addPeriodicTimer(2.0, function (React\EventLoop\TimerInterface $timer) use ($redis, $channel){
$redis->subscribe($channel)->then(function () use ($timer) {
echo 'Now subscribed again' . PHP_EOL;
Loop::cancelTimer($timer);
}, function (Exception $e) {
echo 'Unable to subscribe again: ' . $e->getMessage() . PHP_EOL;
});
});
});