68 lines
1.6 KiB
PHP
68 lines
1.6 KiB
PHP
<?php
|
|
|
|
/**
|
|
* @author Any
|
|
* @description KISS
|
|
* @date 2021年8月10日
|
|
* @version 1.0.0
|
|
*
|
|
* _____LOG_____
|
|
*
|
|
*/
|
|
namespace app\components;
|
|
|
|
|
|
|
|
class LockUtil
|
|
{
|
|
public $enabled = true;
|
|
public $expire_time; //锁有效时长
|
|
|
|
private $lock_name; //锁名称
|
|
private $cx_mch_id;
|
|
private $cx_client_id;
|
|
|
|
|
|
|
|
public function __construct($cx_mch_id, $cx_client_id) {
|
|
$this->cx_mch_id = $cx_mch_id;
|
|
$this->cx_client_id = $cx_client_id;
|
|
$this->expire_time = 86400 * 365;
|
|
}
|
|
|
|
private function get_lock_name($lock_name = null)
|
|
{
|
|
if($lock_name == null){
|
|
$lock_name = \Yii::$app->request->getPathInfo();
|
|
$lock_name = "LK{$this->cx_mch_id}_" . md5($lock_name) . "_" .$this->cx_client_id;
|
|
}
|
|
return $lock_name;
|
|
}
|
|
|
|
|
|
public function acquire($lock_name = null)
|
|
{
|
|
if(!$this->enabled){
|
|
return true;
|
|
}
|
|
$lock_name = $this->get_lock_name($lock_name);
|
|
$lock = FlashStorage::getCache($lock_name);
|
|
if($lock)
|
|
return false;
|
|
return FlashStorage::setCache($lock_name, time(), $this->expire_time);
|
|
}
|
|
|
|
public function release($lock_name = null)
|
|
{
|
|
if(!$this->enabled){
|
|
return true;
|
|
}
|
|
$lock_name = $this->get_lock_name($lock_name);
|
|
$lock = FlashStorage::getCache($lock_name);
|
|
if(!$lock)
|
|
return false;
|
|
return FlashStorage::deleteCache($lock_name);
|
|
}
|
|
}
|
|
|