PHP code example of dealerinspire / laravel-redlock

1. Go to this page and download the library: Download dealerinspire/laravel-redlock 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/ */

    

dealerinspire / laravel-redlock example snippets


use DealerInspire\RedLock\Facades\RedLock;

$product_id = 1;

$lock_object = RedLock::lock($product_id, 3000);

if ($lock_object) {
    $order->submit($product_id);

    RedLock::unlock($lock_token);
    // or
    $lock_object->unlock();
}

use DealerInspire\RedLock\Facades\RedLock;

$product_ids = [1, 2, 3, 5, 7];

$lock_object = RedLock::lock('order-submitter', 3000);

while ($product_ids && $lock_object) {
    $order->submit(array_shift($product_ids));

    $lock_object = RedLock::refreshLock($lock_object);
}

RedLock::unlock($lock_object);
// or
$lock_object->unlock();

use DealerInspire\RedLock\Facades\RedLock;

$product_id = 1;

$result = RedLock::runLocked($product_id, 3000, function () use ($order, $product_id) {
    $order->submit($product_id);
    return true;
});

echo $result ? 'Worked!' : 'Lock not acquired.';

use DealerInspire\RedLock\Facades\RedLock;

$product_ids = [1, 2, 3, 5, 7];

$result = RedLock::runLocked($product_id, 3000, function ($refresh) use ($order, $product_ids) {
    foreach ($product_ids as $product_id) {
        $refresh();
        $order->submit($product_id);
    }
    return true;
});

echo $result ? 'Worked!' : 'Lock lost or never acquired.';

use DealerInspire\RedLock\Traits\QueueWithoutOverlap;

class OrderProductJob
{
    use QueueWithoutOverlap;

    public function __construct($order, $product_id)
    {
        $this->order = $order;
        $this->product_id = $product_id;
    }

    public function handleSync()
    {
        $this->order->submit($this->product_id);
    }
}

use DealerInspire\RedLock\Traits\QueueWithoutOverlap;

class OrderProductsJob
{
    use QueueWithoutOverlap;

    protected $lock_time = 600; // 10 minutes in seconds

    public function __construct($order, array $product_ids)
    {
        $this->order = $order;
        $this->product_ids = $product_ids;
    }

    // We need to define getLockKey() because $product_ids is an array and the
    // automatic key generator can't deal with arrays.
    protected function getLockKey()
    {
        $product_ids = implode(',', $this->product_ids);
        return "OrderProductsJob:{$this->order->id}:{$product_ids}";
    }

    public function handleSync()
    {
        foreach ($this->product_ids as $product_id) {
            $this->refreshLock();
            $this->order->submit($product_id);
        }
    }
}