Created
February 13, 2015 10:30
-
-
Save samsamm777/6ccb42d8260f198b2c28 to your computer and use it in GitHub Desktop.
Example use of predis transactions to do check and set conditional updates. Running this example from multiple threads will maintain a consistent increment value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Our redis client | |
$redis = $this->getContainer()->get("redis_client"); | |
// Set the key | |
$key = 'my_key'; | |
// predis transaction options | |
$options = array( | |
'cas' => true, // Initialize with support for CAS operations | |
'watch' => $key, // Key that needs to be WATCHed to detect changes | |
'retry' => 3, // Number of retries on aborted transactions, after | |
// which the client bails out with an exception. | |
); | |
// Loop for example purposes | |
while(true) { | |
// try the redis transaction, it will fail if the watched key changes | |
// and throw an exception. | |
try { | |
$responses = $redis->transaction($options, function ($tx) use ($key) { | |
// get our value | |
$value = $tx->get($key); | |
// increment value | |
$value = $value + 1; | |
$tx->multi(); // With CAS, MULTI *must* be explicitly invoked. | |
// set new value | |
$tx->set($key, $value); | |
$tx->get($key); | |
}); | |
} catch (\Predis\Transaction\AbortedMultiExecException $e) { | |
continue; | |
} | |
if ($responses) { | |
$output->writeln($responses[1]); | |
} | |
usleep(500); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment