MultiExecTransactionsWithCAS.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. require_once 'SharedConfigurations.php';
  3. /*
  4. This is an implementation of an atomic client-side ZPOP using the support for
  5. check-and-set (CAS) operations with MULTI/EXEC transactions, as described in
  6. "WATCH explained" from http://redis.io/topics/transactions
  7. First, populate your database with a tiny sample data set:
  8. ./redis-cli
  9. SELECT 15
  10. ZADD zset 1 a
  11. ZADD zset 2 b
  12. ZADD zset 3 c
  13. */
  14. function zpop($client, $zsetKey) {
  15. $element = null;
  16. $options = array(
  17. 'cas' => true, // Initialize with support for CAS operations
  18. 'watch' => $zsetKey, // Key that needs to be WATCHed to detect changes
  19. );
  20. $tx = $client->multiExec($options);
  21. @list($element) = $tx->zrange($zsetKey, 0, 0);
  22. if (isset($element)) {
  23. $tx->multi(); // With CAS, MULTI *must* be explicitly invoked.
  24. $tx->zrem($zsetKey, $element);
  25. $tx->exec();
  26. }
  27. return $element;
  28. }
  29. $redis = new Predis_Client($single_server, 'dev');
  30. $zpopped = zpop($redis, 'zset');
  31. echo isset($zpopped) ? "ZPOPed $zpopped" : "Nothing to ZPOP!", "\n";
  32. ?>