PHP code example of msmm / hyperf-redis-lock

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

    

msmm / hyperf-redis-lock example snippets


/**
 * @var RedisLock
 */
protected $redis;

public function __construct(RedisFactory $redisFactory)
{
    $this->redis = $redisFactory->get('default');
}

public function lock(ResponseInterface $response)
{
    // 初始化RedisLock 参数:redis实例 锁名称 超时时间
    $lock = new RedisLock($this->redis, 'lock', 20);
    // 非阻塞式获取锁
    $res = $lock->get(function () {
        sleep(10);
        return [123];
    });
    return $response->json($res);
}

/**
 * @return \Psr\Http\Message\ResponseInterface
 */
public function lockA(ResponseInterface $response)
{
    try {
        // 初始化RedisLock 参数:redis实例 锁名称 超时时间
        $lock = new RedisLock($this->redis, 'lock', 4);
        // 阻塞式
        $res = $lock->block(4, function () {
            return [456];
        });
        return $response->json(['res' => $res]);
    // 捕获超时异常 超时处理
    } catch (LockTimeoutException $exception) {
        var_dump('lockA lock check timeout');
        return $response->json(['res' => false, 'message' => '超时']);
    }
}