PHP code example of motian / lock

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

    

motian / lock example snippets


    'providers' => [
        // ...
        Latrell\Lock\LockServiceProvider::class,
    ]

    'aliases' => [
        // ...
        'Lock' => Latrell\Lock\Facades\Lock::class,
    ]

// 防止商品超卖。
$key = 'Goods:' . $goods_id;
Lock::granule($key, function() use($goods_id) {
    $goods = Goods::find($goods_id);
    if ($goods->stock > 0) {
        // ...
    }
});

// synchronized 是 granule的别名
try {
    $key = md5($user_id . ':' . $udid); // 用户ID+设备ID,防止重复下单
    Lock::synchronized($key, function() use($data) {
        $orderService->createOrder($data)
        // ... 
    }, 0);
} catch (AcquireFailedException $e) {
    // 请求过于频繁,请稍后再试
}


// 锁名称。
$key = 'Goods:' . $goods_id;

// **注意:除非特别自信,否则一定要记得捕获异常,保证解锁动作。**
try {
    // 上锁成功(max_timeout 为0时不会等待当前持有锁的任务运行完成)
    if (Lock::acquire($key, 0)) { 
        // acquire 为true表示上锁成功,false表示锁被占用或上锁等待超时 
        // 第二个参数指定上锁最大超时时间(秒),不指定则默认使用配置文件设置
        // 逻辑单元。
        $goods = Goods::find($goods_id);
        if ( $goods->stock > 0 ) {
            // ...
        }
    }
} finally {
    // 解锁。
    Lock::release($key);
}