Commit 9a850e97 by 刘旋尧

redlock

parents
vendor
composer.lock
{
"name": "usual2970/red-lock",
"description": "redis lock",
"require": {
"predis/predis": "^1.1"
},
"authors": [
{
"name": "刘旋尧",
"email": "536464346@qq.com"
}
],
"autoload":{
"psr-4":{
"usual2970\\redlock\\":"src/"
}
}
}
<?php
namespace usual2970\redlock;
use Predis;
class Lock
{
public $addr = '';
private $client;
private $randomStr;
private $timeout = 200;
const LOCK_PREFIX = "LOCK_";
public function __construct($addr = '')
{
if ($addr) {
$this->addr = $addr;
}
if ($this->addr) {
$this->init();
}
}
public function init()
{
parent::init();
$this->client = new Predis\Client($this->addr);
$this->randomStr = $this->randomStr();
}
public function lock($key)
{
$rs = $this->client->set(self::LOCK_PREFIX . $key, $this->randomStr, 'NX', 'PX', $this->timeout);
return $rs ? true : false;
}
public function unLock($key)
{
$val = $this->client->get(self::LOCK_PREFIX . $key);
if ($this->randomStr === $val) {
$this->client->del(self::LOCK_PREFIX . $key);
}
}
private function randomStr()
{
return md5(microtime() . rand(10000000, 99999999));
}
}
<?php
require dirname(__FILE__) . '/vendor/autoload.php';
use usual2970\redlock\Lock;
$lock = new Lock("tcp://127.0.0.1:16379");
$rs = $lock->lock('test');
if ($rs) {
echo 'get lock successed\n';
} else {
echo 'get lock failed\n';
}
$rs = $lock->unLock('test');
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment