如何为 Zend Cache Storage 设置过期时间? [英] How do I set expire time for Zend Cache Storage?

查看:30
本文介绍了如何为 Zend Cache Storage 设置过期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Zend 文件系统缓存中存储一​​些 XML 并让它在 30 分钟后过期.如何设置缓存持续时间/到期时间?我将 Zend 缓存用作组件,而不是在完整 ZF2 应用程序的上下文中.

I would like to store some XML in a Zend filesystem cache and have it expire after 30 minutes. How does one set the cache duration / expiry? I am using Zend cache as a component and not in the context of a full ZF2 application.

$cache   = \Zend\Cache\StorageFactory::factory(array(
    'adapter' => array(
        'name' => 'filesystem',
        'ttl' => 60, // kept short during testing
        'options' => array('cache_dir' => __DIR__.'/cache'),
    ),
    'plugins' => array(
        // Don't throw exceptions on cache errors
        'exception_handler' => array(
            'throw_exceptions' => false
        ),
    )
));
$key    = 'spektrix-events';   
$events = new SimpleXMLELement($cache->getItem($key, $success));

if (!$success) {
    $response = $client->setMethod('GET')->send();
    $events = new SimpleXMLElement($response->getContent());
    $cache->setItem('spektrix-events', $events->asXML());
}


var_dump($cache->getMetadata($key)); // the mtime on the file stays the same as does timestamp from ls -al in a terminal.

如何设置过期时间,然后检查缓存是否已过期?上面的代码好像没有在 60 秒后使缓存过期(.dat 文件的时间戳没有改变)

How do I set an expiration time and then subsequently check if the cache has expired? The above code does not seem to expire the cache after 60 seconds (the .dat file's timestamp does not change)

推荐答案

您是否尝试过在适配器选项中设置选项 ttl?

Have you tried to set option ttl in adapter options?

'adapter' => array(
    'name' => 'filesystem',
    'options' => array(
        'cache_dir' => __DIR__.'/cache',
        'ttl' => 3600,
    ),
),

ZF 文档 甚至还有很好的快速入门示例,其中显示了 TTL.

ZF documentation has even nice quick start examples, where TTL is presented.

我已经测试了下一个脚本,并且 TTL 正常工作.你在别处有问题.

I have tested next script, and TTL is working like it should. You have problem elsewhere.

$cache = Zend\Cache\StorageFactory::factory(array(
    'adapter' => array(
        'name'    => 'filesystem',
        'options' => array('ttl' => 5),
    ),
));

$cache->setItem('a', 'b');
for ($i = 1; $i <= 7; $i++) {
    sleep(1);
    echo "var_dump on {$i}th second ... ";
    var_dump($cache->getItem('a'));
}

输出是:

var_dump on 1th second ... string(1) "b"
var_dump on 2th second ... string(1) "b"
var_dump on 3th second ... string(1) "b"
var_dump on 4th second ... string(1) "b"
var_dump on 5th second ... NULL
var_dump on 6th second ... NULL
var_dump on 7th second ... NULL

这篇关于如何为 Zend Cache Storage 设置过期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆