MasterSlaveReplicationComplex.php 2.5 KB

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