• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP shared memory cache

php 搞代码 4年前 (2022-01-23) 16次浏览 已收录 0个评论
文章目录[隐藏]

PHP shared memory cache

引子

最近在写PHP的时候,需要使用内存缓存,大家都知道有比较成熟的基于memcached,redis,以及apc等缓存。但是不是要装插件就是要第三方软件支持。在小项目中用起来不是很方便!

实现

shmop_*

所以打算使用php的shared memory的shmop_*前缀的API来实现一个简单的缓存接口。
此函数支持两种调用方式,可以设置和获取缓存。设置的时候还能一并设置缓存过期时间。

  function cache($key, $val=null, $expire=100) {      static $_caches = null;      static $_shm = null;      if ( null === $_shm ) $_shm = @shmop_open(ftok('mcache.solt'),              'c', 0755, config('cache.size', null, 10485760));      if ( null === $_caches && $_shm && ($size = intval(shmop_read($_shm, 0, 10))))          $_caches = $size ? @unserialize(@shmop_read($_shm, 10, $size)) : array();      if (($time = time()) && $val && $expire){          $_caches[$key] = array($time + intval($expire), $val);          if($_shm && ($size = @shmop_write($_shm, serialize(array_filter($_caches, fu<div style="color:transparent">!本文来源gaodai.ma#com搞##代!^码网(</div><sup>搞gaodaima代码</sup>nction($  n)use($time){return $n[0] > $time;})), 10)))              @shmop_write($_shm, sprintf('%10d', $size), 0);          return $val;      }      return (isset($_caches[$key]) && $_caches[$key][0] > $time) ? $_caches[$key][1] : null;  }

不过有个缺点每次load cache的时候需要全部一起load,然后反序列化保存到静态数组里面。只能缓存一些比较小的数据。如果数据过大会不能更新缓存。

我把这个函数和一些其他的基本函数(现在只有8个函数)放在一个utils仓库里面。也可以直接使用 composer require lloydzhou/utils 安装


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP shared memory cache
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址