replication_simple.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 master / slave replication scenarios where write operations
  12. // are performed on the master server and read operations are executed against
  13. // one of the slaves. The behavior of commands or EVAL scripts can be customized
  14. // at will. As soon as a write operation is performed the client switches to the
  15. // master server for all the subsequent requests (either reads and writes).
  16. //
  17. // This example must be executed using the second Redis server configured as the
  18. // slave of the first one (see the "SLAVEOF" command).
  19. //
  20. $parameters = array(
  21. 'tcp://127.0.0.1:6381?role=master&database=15',
  22. 'tcp://127.0.0.1:6382?role=slave&database=15',
  23. );
  24. $options = array('replication' => 'predis');
  25. $client = new Predis\Client($parameters, $options);
  26. // Read operation.
  27. $exists = $client->exists('foo') ? 'yes' : 'no';
  28. $current = $client->getConnection()->getCurrent()->getParameters();
  29. echo "Does 'foo' exist on {$current->role}? $exists.", PHP_EOL;
  30. // Write operation.
  31. $client->set('foo', 'bar');
  32. $current = $client->getConnection()->getCurrent()->getParameters();
  33. echo "Now 'foo' has been set to 'bar' on {$current->role}!", PHP_EOL;
  34. // Read operation.
  35. $bar = $client->get('foo');
  36. $current = $client->getConnection()->getCurrent()->getParameters();
  37. echo "We fetched 'foo' from {$current->role} and its value is '$bar'.", PHP_EOL;
  38. /* OUTPUT:
  39. Does 'foo' exist on slave? yes.
  40. Now 'foo' has been set to 'bar' on master!
  41. We fetched 'foo' from master and its value is 'bar'.
  42. */