我必须在服务器上设置Redis来存储Zend Framework 2中的信息。 现在,我可以存储信息,但我不能给他们一个到期时间,因为他们会在一段时间后自然更新。
我没有找到关于这一步的一些文件,而且在我看来相当模糊。
我的代码:
page: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',
),
),
)
)
);
控制器中的:
..
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
感谢您的帮助!
答案 0 :(得分:0)
看看我的redis工厂:
<?php
namespace Application\Service\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Cache\Storage\Adapter\RedisOptions;
use Zend\Cache\Storage\Adapter\Redis;
class RedisCacheFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$config = $config['redis'];
$options = new RedisOptions();
$options->setServer(
[
'host' => $config["host"],
'port' => $config["port"],
'timeout' => $config["timeout"]
]
);
$options->setTtl(60);
/**
* This is not required, although it will allow to store anything that can be serialized by PHP in Redis
*/
$options->setLibOptions(
[
\Redis::OPT_SERIALIZER => \Redis::SERIALIZER_PHP
]
);
$redis = new Redis($options);
return $redis;
}
}
从示例中可以看出,TTL设置为60秒,并且按预期工作。
答案 1 :(得分:0)
Predis \ Client为setEx:
提供了一个“魔术调用”方法命令执行程序$redis->setEx($key, $expireTTL, $value);
如上所述仔细检查,看看一切都按预期工作:
127.0.0.1:6379>dump your_key 127.0.0.1:6379> ;ttl your_key
希望它有帮助:)!
答案 2 :(得分:0)
你也可以试试这个:
$redis = $this->getServiceLocator()->get('Cache\RedisFactory');
$redis->getOptions()->setTtl(10);
$redis->setItem('test', 'Custom Value');
因此无需在工厂中将其设置为全局。 这项工作对我来说:)
答案 3 :(得分:-1)
return array(
'caches' => array(
'redis' => array (
'adapter' => array (
'name' => 'redis',
'options' => array (
'server' => array (
'host' => 'x.x.x.x',
'port' => x
),
'Ttl' => 10, // Starting with capital letter
'namespace' => 'mycache',
),
),
)
)
);