文件锁
$fp = fopen('/tmp/file.lock',"a+");
if(flock($fp,LOCK_EX)) {
fwrite($fp,"Lock Success");
sleep(5);
flock($fp,LOCK_UN);
} else {
echo "文件正在被其他线程占用";
}
fclose($fp);
redis锁
class Lock {
protected $redis;
protected $lockId;
public function __construct($redis) {
$this->redis = $redis;
}
public function Lock($scene="secKill",$expire=5,$retry=5,$sleep=10000){
$res = false;
while($retry-- >0) {
$value = session_create_id();
$res = $this->redis->set($scene,$value,['NX','EX'=>$expire]);
if($res) {
$this->lockId[$scene] = $value;
var_dump('加锁成功了');
break;
}
echo '尝试获取锁'.PHP_EOL;
usleep($sleep);
}
return $res;
}
public function unLock($scene) {
if (isset($this->lockId[$scene])) {
$id = $this->lockId[$scene];
$value = $this->redis->get($scene);
if($value == $id) {
sleep(5);
var_dump('正常删除');
return $this->redis->del($scene);
}
}
}
}
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$lock = new Lock($redis);
$scene="secKill";
if($lock->Lock($scene,5)) {
var_dump('执行业务逻辑');
sleep(10);
$res = $lock->unLock($scene);
var_dump($res);
var_dump('解锁成功');
return;
}
var_dump('获取锁失败');
|