Created
March 12, 2020 05:54
-
-
Save naveed125/9d555fa3d886bbace3dedaf0749b4fbe to your computer and use it in GitHub Desktop.
Sample code showing usage of SET with NX to acquire a semaphore lock
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
<?php | |
// uses Predis | |
// see https://github.com/nrk/predis | |
use Predis\Client as PredisClient; | |
$client = new PredisClient(); | |
// connect to the local redis server | |
$client->connect(); | |
// synchronized code block | |
$key = 'lock'; | |
if(getLock($client, $key)) { | |
echo "Lock acquired\n"; | |
// do something useful here | |
sleep(1); | |
// release the lock | |
$client->del([$key]); | |
} | |
else { | |
echo ("Failed to acquire lock\n"); | |
} | |
/** | |
* Acquire a lock, notice use of NX parameter | |
* @param PredisClient $client | |
* @param string $key | |
* @return bool | |
*/ | |
function getLock(PredisClient $client, $key) | |
{ | |
// attempts to acquire a lock and | |
for ($i = 0; $i < 3; $i++) { | |
$lock = $client->set($key, time(), 'EX', 3, 'NX'); | |
if ($lock) { | |
return true; | |
} | |
// use exponential back-off when retrying | |
usleep(100 * ($i + 1)); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment