搜索
首页后端开发php教程PHP实现的memcache环形队列类实例

本文实例讲述了PHP实现的memcache环形队列类。分享给大家供大家参考。具体如下:

这里介绍了PHP实现的memcache环形队列类。没咋学过数据结构,因为业务需要,所以只是硬着头皮模拟的! 参考PHP memcache 队列代码。为使队列随时可入可出,且不受int长度越界危险(单链采取Head自增的话不作处理有越界可能),所以索性改写成环形队列。可能还有BUG,忘见谅!

<?php/** * PHP memcache 环形队列类 * 原作者 LKK/lianq.net * 修改 FoxHunter * 因业务需要只保留的队列中的Pop和Push,修改过期时间为0即永久 */class MQueue{ public static $client; private $expire; //过期时间,秒,1~2592000,即30天内 private $sleepTime; //等待解锁时间,微秒 private $queueName; //队列名称,唯一值 private $retryNum; //尝试次数 private $MAXNUM; //最大队列容量 private $canRewrite; //是否可以覆写开关,满出来的内容从头部开始覆盖重写原来的数据 private $HEAD; //下一步要进入的指针位置 private $TAIL; //下一步要进入的指针位置 private $LEN; //队列现有长度 const LOCK_KEY = '_Fox_MQ_LOCK_'; //锁存储标示 const LENGTH_KEY = '_Fox_MQ_LENGTH_'; //队列现长度存储标示 const VALU_KEY = '_Fox_MQ_VAL_'; //队列键值存储标示 const HEAD_KEY = '_Fox_MQ_HEAD_'; //队列HEAD指针位置标示 const TAIL_KEY = '_Fox_MQ_TAIL_'; //队列TAIL指针位置标示 /*  * 构造函数  * 对于同一个$queueName,实例化时必须保障构造函数的参数值一致,否则pop和push会导队列顺序混乱  */ public function __construct($queueName = '', $maxqueue = 1, $canRewrite = false, $expire = 0, $config = '') {  if (empty($config)) {   self::$client = memcache_pconnect('127.0.0.1', 11211);  } elseif (is_array($config)) { //array('host'=>'127.0.0.1','port'=>'11211')   self::$client = memcache_pconnect($config['host'], $config['port']);  } elseif (is_string($config)) { //"127.0.0.1:11211"   $tmp   = explode(':', $config);   $conf['host'] = isset($tmp[0]) ? $tmp[0] : '127.0.0.1';   $conf['port'] = isset($tmp[1]) ? $tmp[1] : '11211';   self::$client = memcache_pconnect($conf['host'], $conf['port']);  }  if (!self::$client)   return false;  ignore_user_abort(true); //当客户断开连接,允许继续执行  set_time_limit(0); //取消脚本执行延时上限  $this->access  = false;  $this->sleepTime = 1000;  $expire   = (empty($expire)) ? 0 : (int) $expire + 1;  $this->expire  = $expire;  $this->queueName = $queueName;  $this->retryNum = 20000;  $this->MAXNUM  = $maxqueue != null ? $maxqueue : 1;  $this->canRewrite = $canRewrite;  $this->getHeadAndTail();  if (!isset($this->HEAD) || empty($this->HEAD))   $this->HEAD = 0;  if (!isset($this->TAIL) || empty($this->TAIL))   $this->TAIL = 0;  if (!isset($this->LEN) || empty($this->LEN))   $this->LEN = 0; } //获取队列首尾指针信息和长度 private function getHeadAndTail() {  $this->HEAD = (int) memcache_get(self::$client, $this->queueName . self::HEAD_KEY);  $this->TAIL = (int) memcache_get(self::$client, $this->queueName . self::TAIL_KEY);  $this->LEN = (int) memcache_get(self::$client, $this->queueName . self::LENGTH_KEY); } // 利用memcache_add原子性加锁 private function lock() {  if ($this->access === false) {   $i = 0;   while (!memcache_add(self::$client, $this->queueName . self::LOCK_KEY, 1, false, $this->expire)) {    usleep($this->sleepTime);    @$i++;    if ($i > $this->retryNum) { //尝试等待N次     return false;     break;    }   }   return $this->access = true;  }  return false; } //更新头部指针指向,指向下一个位置 private function incrHead() {  //$this->getHeadAndTail(); //获取最新指针信息 ,由于本方法体均在锁内调用,其锁内已调用了此方法,本行注释  $this->HEAD++; //头部指针下移  if ($this->HEAD >= $this->MAXNUM) {   $this->HEAD = 0; //边界值修正  }  ;  $this->LEN--; //Head的移动由Pop触发,所以相当于数量减少  if ($this->LEN < 0) {   $this->LEN = 0; //边界值修正  }  ;  memcache_set(self::$client, $this->queueName . self::HEAD_KEY, $this->HEAD, false, $this->expire); //更新  memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //更新 } //更新尾部指针指向,指向下一个位置 private function incrTail() {  //$this->getHeadAndTail(); //获取最新指针信息,由于本方法体均在锁内调用,其锁内已调用了此方法,本行注释  $this->TAIL++; //尾部指针下移  if ($this->TAIL >= $this->MAXNUM) {   $this->TAIL = 0; //边界值修正  }  ;  $this->LEN++; //Head的移动由Push触发,所以相当于数量增加  if ($this->LEN >= $this->MAXNUM) {   $this->LEN = $this->MAXNUM; //边界值长度修正  }  ;  memcache_set(self::$client, $this->queueName . self::TAIL_KEY, $this->TAIL, false, $this->expire); //更新  memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //更新 } // 解锁 private function unLock() {  memcache_delete(self::$client, $this->queueName . self::LOCK_KEY);  $this->access = false; } //判断是否满队列 public function isFull() {  //外部直接调用的时候由于没有锁所以此处的值是个大概值,并不很准确,但是内部调用由于在前面有lock,所以可信  if ($this->canRewrite)   return false;  return $this->LEN == $this->MAXNUM ? true : false; } //判断是否为空 public function isEmpty() {  //外部直接调用的时候由于没有锁所以此处的值是个大概值,并不很准确,但是内部调用由于在前面有lock,所以可信  return $this->LEN == 0 ? true : false; } public function getLen() {  //外部直接调用的时候由于没有锁所以此处的值是个大概值,并不很准确,但是内部调用由于在前面有lock,所以可信  return $this->LEN; } /*  * push值  * @param mixed 值  * @return bool  */ public function push($data = '') {  $result = false;  if (empty($data))   return $result;  if (!$this->lock()) {   return $result;  }  $this->getHeadAndTail(); //获取最新指针信息  if ($this->isFull()) { //只有在非覆写下才有Full概念   $this->unLock();   return false;  }  if (memcache_set(self::$client, $this->queueName . self::VALU_KEY . $this->TAIL, $data, MEMCACHE_COMPRESSED, $this->expire)) {   //当推送后,发现尾部和头部重合(此时指针还未移动),且右边仍有未由Head读取的数据,那么移动Head指针,避免尾部指针跨越Head   if ($this->TAIL == $this->HEAD && $this->LEN >= 1) {    $this->incrHead();   }   $this->incrTail(); //移动尾部指针   $result = true;  }  $this->unLock();  return $result; } /*  * Pop一个值  * @param [length] int 队列长度  * @return array  */ public function pop($length = 0) {  if (!is_numeric($length))   return false;  if (!$this->lock())   return false;  $this->getHeadAndTail();  if (empty($length))   $length = $this->LEN; //默认读取所有  if ($this->isEmpty()) {   $this->unLock();   return false;  }  //获取长度超出队列长度后进行修正  if ($length > $this->LEN)   $length = $this->LEN;  $data = $this->popKeyArray($length);  $this->unLock();  return $data; } /*  * pop某段长度的值  * @param [length] int 队列长度  * @return array  */ private function popKeyArray($length) {  $result = array();  if (empty($length))   return $result;  for ($k = 0; $k < $length; $k++) {   $result[] = @memcache_get(self::$client, $this->queueName . self::VALU_KEY . $this->HEAD);   @memcache_delete(self::$client, $this->queueName . self::VALU_KEY . $this->HEAD, 0);   //当提取值后,发现头部和尾部重合(此时指针还未移动),且右边没有数据,即队列中最后一个数据被完全掏空,此时指针停留在本地不移动,队列长度变为0   if ($this->TAIL == $this->HEAD && $this->LEN <= 1) {    $this->LEN = 0;    memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //更新    break;   } else {    $this->incrHead(); //首尾未重合,或者重合但是仍有未读取出的数据,均移动HEAD指针到下一处待读取位置   }  }  return $result; } /*  * 重置队列  * * @return NULL  */ private function reset($all = false) {  if ($all) {   memcache_delete(self::$client, $this->queueName . self::HEAD_KEY, 0);   memcache_delete(self::$client, $this->queueName . self::TAIL_KEY, 0);   memcache_delete(self::$client, $this->queueName . self::LENGTH_KEY, 0);  } else {   $this->HEAD = $this->TAIL = $this->LEN = 0;   memcache_set(self::$client, $this->queueName . self::HEAD_KEY, 0, false, $this->expire);   memcache_set(self::$client, $this->queueName . self::TAIL_KEY, 0, false, $this->expire);   memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, 0, false, $this->expire);  } } /*  * 清除所有memcache缓存数据  * @return NULL  */ public function memFlush() {  memcache_flush(self::$client); } public function clear($all = false) {  if (!$this->lock())   return false;  $this->getHeadAndTail();  $Head = $this->HEAD;  $Length = $this->LEN;  $curr = 0;  for ($i = 0; $i < $Length; $i++) {   $curr = $this->$Head + $i;   if ($curr >= $this->MAXNUM) {    $this->HEAD = $curr = 0;   }   @memcache_delete(self::$client, $this->queueName . self::VALU_KEY . $curr, 0);  }  $this->unLock();  $this->reset($all);  return true; }}

希望本文所述对大家的php程序设计有所帮助。

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP与Python:了解差异PHP与Python:了解差异Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

php:死亡还是简单地适应?php:死亡还是简单地适应?Apr 11, 2025 am 12:13 AM

PHP不是在消亡,而是在不断适应和进化。1)PHP从1994年起经历多次版本迭代,适应新技术趋势。2)目前广泛应用于电子商务、内容管理系统等领域。3)PHP8引入JIT编译器等功能,提升性能和现代化。4)使用OPcache和遵循PSR-12标准可优化性能和代码质量。

PHP的未来:改编和创新PHP的未来:改编和创新Apr 11, 2025 am 12:01 AM

PHP的未来将通过适应新技术趋势和引入创新特性来实现:1)适应云计算、容器化和微服务架构,支持Docker和Kubernetes;2)引入JIT编译器和枚举类型,提升性能和数据处理效率;3)持续优化性能和推广最佳实践。

您什么时候使用特质与PHP中的抽象类或接口?您什么时候使用特质与PHP中的抽象类或接口?Apr 10, 2025 am 09:39 AM

在PHP中,trait适用于需要方法复用但不适合使用继承的情况。1)trait允许在类中复用方法,避免多重继承复杂性。2)使用trait时需注意方法冲突,可通过insteadof和as关键字解决。3)应避免过度使用trait,保持其单一职责,以优化性能和提高代码可维护性。

什么是依赖性注入容器(DIC),为什么在PHP中使用一个?什么是依赖性注入容器(DIC),为什么在PHP中使用一个?Apr 10, 2025 am 09:38 AM

依赖注入容器(DIC)是一种管理和提供对象依赖关系的工具,用于PHP项目中。DIC的主要好处包括:1.解耦,使组件独立,代码易维护和测试;2.灵活性,易替换或修改依赖关系;3.可测试性,方便注入mock对象进行单元测试。

与常规PHP阵列相比,解释SPL SplfixedArray及其性能特征。与常规PHP阵列相比,解释SPL SplfixedArray及其性能特征。Apr 10, 2025 am 09:37 AM

SplFixedArray在PHP中是一种固定大小的数组,适用于需要高性能和低内存使用量的场景。1)它在创建时需指定大小,避免动态调整带来的开销。2)基于C语言数组,直接操作内存,访问速度快。3)适合大规模数据处理和内存敏感环境,但需谨慎使用,因其大小固定。

PHP如何安全地上载文件?PHP如何安全地上载文件?Apr 10, 2025 am 09:37 AM

PHP通过$\_FILES变量处理文件上传,确保安全性的方法包括:1.检查上传错误,2.验证文件类型和大小,3.防止文件覆盖,4.移动文件到永久存储位置。

什么是无效的合并操作员(??)和无效分配运算符(?? =)?什么是无效的合并操作员(??)和无效分配运算符(?? =)?Apr 10, 2025 am 09:33 AM

JavaScript中处理空值可以使用NullCoalescingOperator(??)和NullCoalescingAssignmentOperator(??=)。1.??返回第一个非null或非undefined的操作数。2.??=将变量赋值为右操作数的值,但前提是该变量为null或undefined。这些操作符简化了代码逻辑,提高了可读性和性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!