replication_sentinel.php 2.1KB

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. // 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. // Instead of connection parameters pointing to redis nodes, we provide a list
  18. // of instances of redis-sentinel. Users should always provide a timeout value
  19. // low enough to not hinder operations just in case a sentinel is unreachable
  20. // but Predis uses a default value of 100 milliseconds for sentinel parameters
  21. // without an explicit timeout value.
  22. //
  23. // NOTE: in real-world scenarios sentinels should be running on different hosts!
  24. $sentinels = array(
  25. 'tcp://127.0.0.1:5380?timeout=0.100',
  26. 'tcp://127.0.0.1:5381?timeout=0.100',
  27. 'tcp://127.0.0.1:5382?timeout=0.100',
  28. );
  29. $client = new Predis\Client($sentinels, array(
  30. 'replication' => 'sentinel',
  31. 'service' => 'mymaster',
  32. ));
  33. // Read operation.
  34. $exists = $client->exists('foo') ? 'yes' : 'no';
  35. $current = $client->getConnection()->getCurrent()->getParameters();
  36. echo "Does 'foo' exist on {$current->alias}? $exists.", PHP_EOL;
  37. // Write operation.
  38. $client->set('foo', 'bar');
  39. $current = $client->getConnection()->getCurrent()->getParameters();
  40. echo "Now 'foo' has been set to 'bar' on {$current->alias}!", PHP_EOL;
  41. // Read operation.
  42. $bar = $client->get('foo');
  43. $current = $client->getConnection()->getCurrent()->getParameters();
  44. echo "We fetched 'foo' from {$current->alias} and its value is '$bar'.", PHP_EOL;
  45. /* OUTPUT:
  46. Does 'foo' exist on slave-127.0.0.1:6381? yes.
  47. Now 'foo' has been set to 'bar' on master!
  48. We fetched 'foo' from master and its value is 'bar'.
  49. */