PHP code example of libratechie / think-distributed-lock

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

    

libratechie / think-distributed-lock example snippets


return [
    // 默认使用的数据库连接配置
    'default'         => env('LOCK_DRIVER', 'redis'),
    'connections'     => [
        'redis' => [
            // 驱动方式
            'type' => 'redis',
            // 服务器地址
            'host' => env('LOCK_REDIS_HOST', '127.0.0.1'),
            // 端口
            'port' => env('LOCK_REDIS_PORT', 6379),
            // 锁前缀
            'prefix' => env('LOCK_REDIS_PREFIX', 'lock_'),

        ],
    ]
];

use DistributedLock\DisLockFactory;

// 初始化锁
$dis_lock = DisLockFactory::getInstance();

public function orderCreate($buyer_id)
{
    $lock_key = "user_submit_order:{$buyer_id}";
    
    // 尝试获取锁(等待10秒)
    if (!$lock = $dis_lock->lock($lock_key, 10)) {
        return json(['error' => '操作过于频繁,请稍后重试']);
    }

    try {
        // 你的业务逻辑...
        // 例如:订单创建、库存扣减等
        
        return json(['status' => 'success']);
    } catch (\Exception $e) {
        // 异常处理...
        return json(['error' => $e->getMessage()]);
    } finally {
        // 确保最终释放锁
        $dis_lock->unlock($lock_key);
    }
}