PHP code example of kelunik / redis-mutex

1. Go to this page and download the library: Download kelunik/redis-mutex library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kelunik / redis-mutex example snippets


$mutex = new Mutex(...);

// ...

try {
    $token = bin2hex(random_bytes(16));
    yield $mutex->lock($sessionId, $token);

    // Code here will only be executed in one client at a time.
    // If it takes longer than your specified TTL, you have to
    // renew the lock, see next example.

    yield $mutex->unlock($sessionId, $token);
} catch (MutexException $e) {
    // ...
}

$mutex = new Mutex(...);
$locks = [];

Loop::repeat(1000, function () use ($mutex, $locks) {
    foreach ($locks as $id => $token) {
        $mutex->renew($id, $token);
    }
});

// ...

try {
    $token = bin2hex(random_bytes(16));
    yield $mutex->lock($sessionId, $token);
    $locks[$sessionId] = $token;

    // Code here will only be executed in one client at a time.
    // Your lock will automatically be renewed by the reactor
    // repeat above. Don't do blocking things here (you should never
    // do that with Amp anyway), otherwise the reactor will not
    // be able to schedule the renewal.

    unset($locks[$sessionId]);
    yield $mutex->unlock($sessionId, $token);
} catch (MutexException $e) {
    // ...
}