PHP shared memory cache

來源:互聯網
上載者:User
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, function($  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 安裝

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.