juneym/zf2-cache-mongo

使用 MongoDB 的 TTL 集合功能的 ZF2 缓存存储兼容库

0.5.0 2016-06-24 04:44 UTC

This package is not auto-updated.

Last update: 2024-09-25 13:21:42 UTC


README

使用 MongoDB 的 TTL 集合功能的 ZF2 缓存存储兼容库

概述

似乎很少有人对创建一个 MongoDB 兼容的 ZF2 缓存存储后端库感兴趣,因此有这个项目。

该库使用 MongoDB v2.2 中引入的生存时间(TTL)集合功能

使用库

  1. 更新你的 composer.json(如果你有)

    (待添加)

  2. 实例化库

    $options = array( 'dsn' => 'mongodb://127.0.0.1', 'mongoOptions' => array(/* 任何有效的 \Mongo 或 \MongoClient 选项 */), 'dbname' => 'cachedb', 'collection' => 'cache', 'ttl' => 10, 'namespace' => 'stl' );

    $mongoCache = new \Juneym\Cache\Storage\Adapter\Mongo($options); $cacheKey = md5('This is a sample key');

    $created = $mongoCache->setItem($cacheKey, array('x' => 12345, 'y' => 'ABCDEF' . rand(0,10000))); if (!$created) { die("使用键缓存: " . $cacheKey . "\n"); }

    $data = $mongoCache->getItem($cacheKey); print_r($data); unset($mongoCache);

缓存项属性

有些应用程序需要在 MongoDB 中的缓存记录中包含额外的元数据,例如 "当前页面地址" 或 "远程主机 IP"。为此,使用 setCacheItemAttributes(array) 将数组属性附加到缓存项。当检索具有属性的项时,数据可通过 attr 键访问。以下是测试文件的一个片段。

    public function testCanAttachCacheItemAttributes()
    {
        $mongoCache = new Storage\Adapter\Mongo($this->options);

        $cacheKey = md5('this is a test key with attributes' . __METHOD__);
        $itemAttribute = array(
            'current_page' => 'http://hello-world.com/about-us.html',
            'browser' => 'Firefox'
        );
        $mongoCache->setCacheItemAttributes($itemAttribute);
        $result = $mongoCache->setItem($cacheKey, array('x' => 11111, 'y' => 'ABCDEF' . rand(0,10000)));
        $this->assertTrue($result);
        $data = $mongoCache->getItem($cacheKey);

        $this->assertArrayHasKey('attr', $data);
        $this->assertEquals($itemAttribute['current_page'], $data['attr']['current_page']);
        $this->assertEquals($itemAttribute['browser'], $data['attr']['browser']);

        $itemAttribute1 = $mongoCache->getCacheItemAttributes();
        $this->assertTrue(is_array($itemAttribute1));
        $this->assertTrue(empty($itemAttribute1));

        unset($mongoCache);
    }

关于 TTL 索引和缓存过期

缓存数据将过期的有两种方式。

  1. 当当前时间与缓存项的 created 时间之差超过缓存项的 ttl 值(以秒为单位)时
  2. 当记录的 created 值远远超过 MongoDB 的缓存集合 TTL 索引(expireAfterSeconds)。请注意,MongoDB 的垃圾回收每 60 秒运行一次,因此如果缓存项仍然可用,请不要感到惊讶。MongoDB 的垃圾回收器最终会在后台删除所有符合条件的记录。

所需索引

假设缓存数据库名为 "cachedb",集合名为 "cache",以下索引是必需的

use cachedb
db.cache.ensureIndex({ns:1}, {background:true});
db.cache.ensureIndex({ns:1, key:1}, {background:true});
db.cache.ensureIndex({ns:1, tags:1}, {background:true});

如果你使用的是低于 v0.2.0 的版本,请使用以下 TTL 索引定义

db.cache.ensureIndex({created:1}, {background:true, expireAfterSeconds: 3600, name: 'colRecordTTl'});

从 v0.2.0 开始,expireAt 字段根据缓存条目创建(或保存)时的 ttl 值填充。使用以下索引强制基于 expireAt 字段的记录自动过期。

db.cache.ensureIndex({created:1, expireAt:1}, {background: true});
db.cache.ensureIndex({expireAt:1}, {expireAfterSeconds: 0, name: 'cache_expire_at'});