PHP code example of lysice / hyperf-redis-lock

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

    

lysice / hyperf-redis-lock example snippets


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

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

public function lock(ResponseInterface $response)
    {
        $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 {
            $lock = new RedisLock($this->redis, 'lock', 4);
            $res = $lock->block(4, function () {
                return [456];
            });
            return $response->json(['res' => $res]);
        // catch the exception
        } catch (LockTimeoutException $exception) {
            var_dump('lockA lock check timeout');
            return $response->json(['res' => false, 'message' => 'timeout']);
        }
    }