pubsub_consumer.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. require __DIR__.'/shared.php';
  11. // Starting from Redis 2.0 clients can subscribe and listen for events published
  12. // on certain channels using a Publish/Subscribe (PUB/SUB) approach.
  13. // Create a client and disable r/w timeout on the socket
  14. $client = new Predis\Client($single_server + array('read_write_timeout' => 0));
  15. // Initialize a new pubsub consumer.
  16. $pubsub = $client->pubSubLoop();
  17. // Subscribe to your channels
  18. $pubsub->subscribe('control_channel', 'notifications');
  19. // Start processing the pubsup messages. Open a terminal and use redis-cli
  20. // to push messages to the channels. Examples:
  21. // ./redis-cli PUBLISH notifications "this is a test"
  22. // ./redis-cli PUBLISH control_channel quit_loop
  23. foreach ($pubsub as $message) {
  24. switch ($message->kind) {
  25. case 'subscribe':
  26. echo "Subscribed to {$message->channel}", PHP_EOL;
  27. break;
  28. case 'message':
  29. if ($message->channel == 'control_channel') {
  30. if ($message->payload == 'quit_loop') {
  31. echo 'Aborting pubsub loop...', PHP_EOL;
  32. $pubsub->unsubscribe();
  33. } else {
  34. echo "Received an unrecognized command: {$message->payload}.", PHP_EOL;
  35. }
  36. } else {
  37. echo "Received the following message from {$message->channel}:",
  38. PHP_EOL, " {$message->payload}", PHP_EOL, PHP_EOL;
  39. }
  40. break;
  41. }
  42. }
  43. // Always unset the pubsub consumer instance when you are done! The
  44. // class destructor will take care of cleanups and prevent protocol
  45. // desynchronizations between the client and the server.
  46. unset($pubsub);
  47. // Say goodbye :-)
  48. $version = redis_version($client->info());
  49. echo "Goodbye from Redis $version!", PHP_EOL;