<?php
/**
* Redis锁操作类
* Date: 2016-06-30
* Author: fdipzone
* Ver: 1.0
*
* Func:
* public lock 获取锁
* public unlock 释放锁
* private connect 连接
*/
class RedisLock { // class start
private $_config;
private $_redis;
/**
* 初始化
* @param Array $config redis连接设定
*/
public function __construct($config=array()){
$this->_config = $config;
$this->_redis = $this->connect();
}
/**
* 获取锁
* @param String $key 锁标识
* @param Int $expire 锁过期时间
* @return Boolean
*/
public function lock($key, $expire=5){
$is_lock = $this->_redis->setnx($key, time()+$expire);
// 不能获取锁
if(!$is_lock){
// 判断锁是否过期
$lock_time = $this->_redis->get($key);
// 锁已过期,删除锁,重新获取
if(time()>$lock_time){
$this->unlock($key);
$is_lock = $this->_redis->setnx($key, time()+$expire);
}
}
return $is_lock? true : false;
}
/**
* 释放锁
* @param String $key 锁标识
* @return Boolean
*/
public function unlock($key){
return $this->_redis->del($key);
}
/**
* 创建redis连接
* @return Link
*/
private function connect(){
try{
$redis = new Redis();
$redis->connect($this->_config['host'],$this->_config['port'],$this->_config['timeout'],$this->_config['reserved'],$this->_config['retry_interval']);
if(empty($this->_config['auth'])){
$redis->auth($this->_config['auth']);
}
$redis->select($this->_config['index']);
}catch(RedisException $e){
throw new Exception($e->getMessage());
return false;
}
return $redis;
}
} // class end
?>
php 使用redis锁限制并发访问类
4星 · 超过85%的资源 需积分: 35 198 浏览量
2016-06-30
22:09:05
上传
评论 6
收藏 1KB ZIP 举报
傲雪星枫
- 粉丝: 2305
- 资源: 74
最新资源
- apk.tw_LineLite_v8a_v.2.17.1_sign.apk
- Elasticsearch实战:构建高效搜索系统的秘诀.zip
- HTML+CSS+JS网页设计:从入门到精通.zip
- 数据库课程设计:从理论到实践的全面指南.zip
- Python闭包:深入理解与应用场景解析.zip
- Win64OpenSSL-3-3-0.exe
- 课高分程设计-基于C++实现的民航飞行与地图简易管理系统-南京航空航天大学
- 航天器遥测数据故障检测系统python源码+文档说明+数据库(课程设计)
- 北京航空航天大学操作系统课设+ppt+实验报告
- 基于Vue+Echarts实现风力发电机中传感器的数据展示监控可视化系统+源代码+文档说明(高分课程设计)
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈