【发布时间】:2014-10-30 15:18:19
【问题描述】:
我有某些代码希望一次只能由一个用户运行。我不想让儿子复杂的锁/会话依赖系统,我只是希望延迟用户请求我们返回一些消息以重试。
代码实际上是ssh/powershell连接所以我想隔离它。
有什么方便的方法吗??
我忘了说它是 laravel/php 代码。
【问题讨论】:
-
您能否向我们展示代码以及您迄今为止尝试过的内容以及您遇到的任何错误/问题,以便我们更好地帮助您?用户如何运行代码?
我有某些代码希望一次只能由一个用户运行。我不想让儿子复杂的锁/会话依赖系统,我只是希望延迟用户请求我们返回一些消息以重试。
代码实际上是ssh/powershell连接所以我想隔离它。
有什么方便的方法吗??
我忘了说它是 laravel/php 代码。
【问题讨论】:
您需要获得某种“锁”。如果没有锁,就没有人访问任何东西。如果有锁,则有人正在访问某些东西,其余的应该等待。最简单的方法是使用文件并获取排他锁来实现这一点。我将发布一个示例类(未经测试)和示例用法。您可以使用以下示例代码派生一个工作示例:
class MyLockClass
{
protected $fh = null;
protected $file_path = '';
public function __construct($file_path)
{
$this->file_path = $file_path;
}
public function acquire()
{
$handler = $this->getFileHandler();
return flock($handler, LOCK_EX);
}
public function release($close = false)
{
$handler = $this->getFileHandler();
return flock($handler, LOCK_UN);
if($close)
{
fclose($handler);
$this->fh = null;
}
}
protected function acquireLock($handler)
{
return flock($handler, LOCK_EX);
}
protected function getFileHandler()
{
if(is_null($this->fh))
{
$this->fh = fopen($this->file_path, 'c');
if($this->fh === false)
{
throw new \Exception(sprintf("Unable to open the specified file: %s", $this->file_path));
}
}
return $this->fh;
}
}
用法:
$lock = new MyLockClass('/my/file/path');
try
{
if($lock->acquire())
{
// Do stuff
$lock->release(true);
}
else
{
// Someone is working, either wait or disconnect the user
}
}
catch(\Exception $e)
{
echo "An error occurred!<br />";
echo $e->getMessage();
}
【讨论】: