replication_sentinel.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. 'service' => 'mymaster',
  32. 'aggregate' => function () {
  33. return function ($sentinels, $options) {
  34. return new SentinelReplication($sentinels, $options->service, $options->connections);
  35. };
  36. },
  37. ));
  38. // Read operation.
  39. $exists = $client->exists('foo') ? 'yes' : 'no';
  40. $current = $client->getConnection()->getCurrent()->getParameters();
  41. echo "Does 'foo' exist on {$current->alias}? $exists.", PHP_EOL;
  42. // Write operation.
  43. $client->set('foo', 'bar');
  44. $current = $client->getConnection()->getCurrent()->getParameters();
  45. echo "Now 'foo' has been set to 'bar' on {$current->alias}!", PHP_EOL;
  46. // Read operation.
  47. $bar = $client->get('foo');
  48. $current = $client->getConnection()->getCurrent()->getParameters();
  49. echo "We fetched 'foo' from {$current->alias} and its value is '$bar'.", PHP_EOL;
  50. /* OUTPUT:
  51. Does 'foo' exist on slave? yes.
  52. Now 'foo' has been set to 'bar' on master!
  53. We fetched 'foo' from master and its value is 'bar'.
  54. */