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/ */
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();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.