<div class="jb51code">
<pre class="brush:PHP;">
<?php
// 使用Memache 作为进程锁
class lock_processlock{
// key 的前缀
protected $sLockKeyPre;
// 重试间隔
protected $iLockRetryInterval;
//重试次数
protected $iLockRetryCount;
//锁的过期时间
protected $iLockCacheTimeout;
// 锁过期后的回调函数
protected $onLockTimeoutFunc;
// memache 的实例
protected $oMemcache;
// 存储memcache失败后重试次数
protected $iMemcacheRetryCount;
public function __construct ($onLockTimeoutFunc=NULL) {
$aLockConfig = get_config('','lock');
$this->sLockKeyPre = self::LOCK_KEY_PRE;
$this->iLockRetryInterval = self::LOCK_RETRY_INTERVAL;
$this->iLockRetryCount =self::LOCK_RETRY_COUNT;
$this->iLockCacheTimeout = self::LOCK_CACHE_TIMEOUT;
$this->iMemcacheRetryCount = self::LOCK_CACHE_TIMEOUT;
if(!$onLockTimeoutFunc){
// 如果加锁不成功则调用回调函数,如果没有回调函数,使用本类中所带的
$onLockTimeoutFunc ='onLockTimeout' ;
}
$this->onLockTimeoutFunc = $onLockTimeoutFunc;
}
/**
连接memcache 服务器
*/
public function connect() {
if (! isset ( $this->oMemcache )) {
$this->oMemcache = new Memcache ();
$this->oMemcache->connect ( '127.0.0.1',11211 );
}
return $this->oMemcache;
}
/*
向MeMcache中<a href="https://www.jb51.cc/tag/tianjia/" target="_blank" class="keywords">添加</a> key
*/
public addMemcache($sKey,$sValue,$iTimeout){
for($i= 0 ; $i<$this->iMemcacheRetryCount){
$bRes = $this->oMemcache->add($sKey,$iTimeout);
if($bRes){
return true ;
}
// 如果加锁不成功,sleep 之后,从新加锁
usleep($this->iLockRetryInterval*1000);
}
return false ;
}
/*
加锁
*/
public function lock($sLockID){
$oMemcache = $this->connect();
$sKey = $this->sLockKeyPre . $sLockID;
// 加锁如果不成功可以多试几次
for($i = 0 ; $i <$this->iLockRetryCount ; $i++){
// 这里设置value 的值可以随便设置
if($this->addMemcache($sKey,'1',$this->iLockCacheTimeout)){
return true ;
}
// 如果加锁不成功,从新加锁
usleep($this->iLockRetryInterval*1000);
}
// 若还不成功,则加锁失败,<a href="https://www.jb51.cc/tag/diaoyong/" target="_blank" class="keywords">调用</a>回调<a href="https://www.jb51.cc/tag/hanshu/" target="_blank" class="keywords">函数</a>,.也就是失败后需要处理的操作
if(is_callable($this->onLockTimeoutFunc)){
// <a href="https://www.jb51.cc/tag/diaoyong/" target="_blank" class="keywords">调用</a><a href="https://www.jb51.cc/tag/hanshu/" target="_blank" class="keywords">函数</a>
call_user_func($this->onLockTimeoutFunc);
}
}
/*
解锁操作
*/
public function unlock($sLockID){
$oMemcache = $this->connect();
$sKey = $this->sLockKeyPre . $sLockID;
// <a href="https://www.jb51.cc/tag/shanchu/" target="_blank" class="keywords">删除</a>key
return $this->oMemcache->delete($sKey);
}
/**
如果加锁不成功,则执行如下操作
*/
public function onLockTimeout(){
echo ("加锁超时");
}
}
// 应用实例
$oLock = new lock_processlock();
$lockResource = "test";
// 加锁
$oLock->lock($lockResource);
// 解锁
$oLock->unlock($lockResource);