replication_complex.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 allows to set Lua scripts as read-only operations for replication.
  12. // This works for both EVAL and EVALSHA and also for the client-side abstraction
  13. // built upon them (Predis\Command\ScriptCommand). This example shows a slightly
  14. // more complex configuration that injects a new script command in the command
  15. // factory used by the client and marks it as a read-only operation so that it
  16. // will be executed on slaves.
  17. use Predis\Command\ScriptCommand;
  18. use Predis\Connection\Replication\MasterSlaveReplication;
  19. use Predis\Replication\ReplicationStrategy;
  20. // ------------------------------------------------------------------------- //
  21. // Define a new script command that returns all the fields of a variable number
  22. // of hashes with a single roundtrip.
  23. class HashMultipleGetAll extends ScriptCommand
  24. {
  25. const BODY = <<<LUA
  26. local hashes = {}
  27. for _, key in pairs(KEYS) do
  28. table.insert(hashes, key)
  29. table.insert(hashes, redis.call('hgetall', key))
  30. end
  31. return hashes
  32. LUA;
  33. public function getScript()
  34. {
  35. return self::BODY;
  36. }
  37. }
  38. // ------------------------------------------------------------------------- //
  39. $parameters = array(
  40. 'tcp://127.0.0.1:6381?role=master&database=15',
  41. 'tcp://127.0.0.1:6382?role=slave&alias=slave-01&database=15',
  42. );
  43. $options = array(
  44. 'commands' => array(
  45. 'hmgetall' => 'HashMultipleGetAll',
  46. ),
  47. 'replication' => function () {
  48. $strategy = new ReplicationStrategy();
  49. $strategy->setScriptReadOnly(HashMultipleGetAll::BODY);
  50. $replication = new MasterSlaveReplication($strategy);
  51. return $replication;
  52. },
  53. );
  54. // ------------------------------------------------------------------------- //
  55. $client = new Predis\Client($parameters, $options);
  56. // Execute the following commands on the master server using redis-cli:
  57. // $ ./redis-cli HMSET metavars foo bar hoge piyo
  58. // $ ./redis-cli HMSET servers master host1 slave host2
  59. $hashes = $client->hmgetall('metavars', 'servers');
  60. $replication = $client->getConnection();
  61. $stillOnSlave = $replication->getCurrent() === $replication->getConnectionByAlias('slave-01');
  62. echo 'Is still on slave? ', $stillOnSlave ? 'YES!' : 'NO!', PHP_EOL;
  63. var_export($hashes);