锁机制处理类

<?php


namespace app\common\library;

use think\Cache;
use think\Exception;

/**
* 锁机制
*/
class Lock
{

public function run($callback, $key, $expire = 10)
{
try {
if (Cache::store('redis')->has($key)) {
throw new LockException('已锁定');
}
$this->getLock($key, 1, $expire);
$result = null;
if (is_callable($callback)) {
$result = call_user_func_array($callback, [$this]);
}
$this->unLock($key);
return $result;
} catch (LockException $e) {
throw $e;
} catch (\Exception $e) {
$this->unLock($key);
throw $e;
} catch (\Throwable $e) {
$this->unLock($key);
throw $e;
}
}

/**
* 获取锁
* @param $name
* @param $key
* @param int $expire
* @return bool
*/
public function getLock($name, $key, $expire = 5)
{
if (Cache::store('redis')->has($name)) {

return false;
}
return Cache::store('redis')->set($name, $key, $expire);
}

/**
* 释放锁
* @param $name
*/
public function unLock($name)
{
Cache::store('redis')->rm($name);
}
}
class LockException extends Exception{ }

调用:

  try {
       $result = (new Lock)->run(function () use () {
              // code
              return true;
          }
        }, $key, 10);
    } catch (Exception $e) {
        return false;
    }

 

posted @ 2020-07-24 10:34  屋顶上的猫。  阅读(125)  评论(0)    收藏  举报