php - ZF2 Redis : how to set expiration time for a key

标签 php caching zend-framework redis zend-framework2

我必须在服务器上设置一个 Redis 来存储来自 Zend Framework 2 的信息。 现在,我可以存储信息,但我不能给它们一个过期时间,因为它们会在一段时间后自然更新。

我还没有找到关于这一步的一些文档,在我看来它相当晦涩。

我的代码:

页面:config/autoload/cache.global.php

return array(
    'caches' => array(
        'redis' => array (
            'adapter' => array (
                'name' => 'redis',
                'lifetime' => 60, //doesn't work
                'options' => array (
                    'server' => array (
                        'host' => 'x.x.x.x',
                        'port' => x
                    ),
                    'ttl' => 10, // seems to have no effect
                    'namespace' => 'mycache',
                ),
            ),
        )
    )
);

在 Controller 中:

..
use Zend\Cache\StorageFactory;
..
        $redis = StorageFactory::factory ($this->getServiceLocator ()
             ->get ('config')['caches']['redis']);

        if ($redis->hasItem ('test')) {
                var_dump($redis->getItem ('test'));
                $redis->removeItem('test');
        } else {
            $redis->addItem('test', 'testtest');
        }
..

我尝试了几种方法,但每次结果都是一样的,Redis 中没有出现过期信息:

127.0.0.1:6379> get mycache:test
"testtest"
127.0.0.1:6379> ttl mycache:test
(integer) -1

感谢您的帮助!

最佳答案

你也可以试试这个:

$redis = $this->getServiceLocator()->get('Cache\RedisFactory');
$redis->getOptions()->setTtl(10);
$redis->setItem('test', 'Custom Value');

因此无需在工厂中进行全局设置。 这对我有用:)

关于php - ZF2 Redis : how to set expiration time for a key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35227982/

相关文章:

php - 使用php解析xml文件时出现问题。 URL 地址不包含 .xml 扩展名

php - 如何为 PHP 的 CLI 启用 mysqli 支持

.net - 如何清除HttpWebRequest的缓存

Java固定内存映射

php - 如何使用图像链接提交表单以使用 JS(无 JQuery)更改表单操作?

php - 订阅包并存储它们

javascript - 在资源有限的浏览器(移动)中管理大型数据集的缓存

php - 清理 magento 缓存时开始和结束标记不匹配 :/Varien/Simplexml/Config. php

php - Zend 表单元素错误不显示

php - 如何添加 View 助手目录(zend 框架)