PHP code example of happysir / distributed-lock

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

    

happysir / distributed-lock example snippets


use Happysir\Lock\RedisLock;
use Swoft\Redis\Pool;
use Swoft\Redis\RedisDb;

return [
    // redis db
    'redis'            => [
        'class'    => RedisDb::class,
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
        'option'   => [
            'prefix'     => 'swoft:',
            'serializer' => Redis::SERIALIZER_NONE
        ]
    ],
    // redis pool
    Pool::DEFAULT_POOL => [
        'class'       => Pool::class,
        'redisDb'     => \bean('redis'),
        'minActive'   => 10,
        'maxActive'   => 20,
        'maxWait'     => 0,
        'maxWaitTime' => 0,
        'maxIdleTime' => 60,
    ],
    // redis lock
    RedisLock::class   => [
        // redis pool
        'pool' => Pool::DEFAULT_POOL,
    ]
];

 declare(strict_types=1);

namespace App\Http\Controller;

use Happysir\Lock\Annotation\Mapping\DistributedLock;
use Swoft\Context\Context;
use Swoft\Http\Message\Request;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Router\Router;
use Swoft\View\Renderer;
use Swoole\Coroutine;
use Throwable;

/**
 * Class HomeController
 * @Controller()
 */
class HomeController
{
    /**
     * @RequestMapping("/")
     * @DistributedLock(key="request.getUriPath()~':'~request.query('id')",ttl=6,type=DistributedLock::RETRY_TO_GET)
     * @throws Throwable
     */
    public function index(Request $request): Response
    {
        Coroutine::sleep(1);
        
        return context()->getResponse();
    }

    /**
     * @RequestMapping("/hello")
     * @DistributedLock(key="hello~':'~request.query('id')",ttl=6,type=DistributedLock::NON_BLOCKING)
     * @throws Throwable
     */
    public function hello(Request $request): Response
    {
        Coroutine::sleep(1);
        
        return context()->getResponse();
    }
}

use Happysir\Lock\RedisLock;
$distributedLock = bean(RedisLock::class);

if (!$distributedLock->tryLock('test', 1)) {
    return false;
}

// 业务逻辑...

$distributedLock->unLock();

use Happysir\Lock\RedisLock;
$distributedLock = bean(RedisLock::class);

// 加锁1s,重试3次
if (!$distributedLock->lock('test', 1, 3)) {
    return false;
}

// 业务逻辑...

$distributedLock->unLock();