replication_sentinel.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // Predis supports redis-sentinel to provide high availability in master / slave
  12. // scenarios. The only but relevant difference with a basic replication scenario
  13. // is that sentinel servers can manage the master server and its slaves based on
  14. // their state, which means that they are able to provide an authoritative and
  15. // updated configuration to clients thus avoiding static configurations for the
  16. // replication servers and their roles.
  17. use Predis\Connection\Aggregate\SentinelReplication;
  18. // Instead of connection parameters pointing to redis nodes, we provide a list
  19. // of instances of redis-sentinel. Users should always provide a timeout value
  20. // low enough to not hinder operations just in case a sentinel is unreachable
  21. // but Predis uses a default value of 100 milliseconds for sentinel parameters
  22. // without an explicit timeout value.
  23. //
  24. // NOTE: in real-world scenarios sentinels should be running on different hosts!
  25. $sentinels = array(
  26. 'tcp://127.0.0.1:5380?timeout=0.100',
  27. 'tcp://127.0.0.1:5381?timeout=0.100',
  28. 'tcp://127.0.0.1:5382?timeout=0.100',
  29. );
  30. $client = new Predis\Client($sentinels, array(
  31. 'replication' => 'sentinel',
  32. 'service' => 'mymaster',
  33. ));
  34. // Read operation.
  35. $exists = $client->exists('foo') ? 'yes' : 'no';
  36. $current = $client->getConnection()->getCurrent()->getParameters();
  37. echo "Does 'foo' exist on {$current->alias}? $exists.", PHP_EOL;
  38. // Write operation.
  39. $client->set('foo', 'bar');
  40. $current = $client->getConnection()->getCurrent()->getParameters();
  41. echo "Now 'foo' has been set to 'bar' on {$current->alias}!", PHP_EOL;
  42. // Read operation.
  43. $bar = $client->get('foo');
  44. $current = $client->getConnection()->getCurrent()->getParameters();
  45. echo "We fetched 'foo' from {$current->alias} and its value is '$bar'.", PHP_EOL;
  46. /* OUTPUT:
  47. Does 'foo' exist on slave-127.0.0.1:6381? yes.
  48. Now 'foo' has been set to 'bar' on master!
  49. We fetched 'foo' from master and its value is 'bar'.
  50. */