如何缓存Twitter API的结果? [英] how to cache the twitter api result?

查看:178
本文介绍了如何缓存Twitter API的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想缓存twitter api结果的结果并将其显示给用户。

I would like to cache the result of the twitter api result and display them to users..

缓存结果的最佳方法是什么?

What's the best method to cache the result?

我正在考虑根据时间限制将结果写入文件中。是否可以使用其他方法?

I'm thinking a writing the result into a file based on a time limit.. Is that ok or any other method should be used?

最重要的是,理想的缓存时间是多少?我想显示来自Twitter的最新内容,但是Twitter api有请求限制。.
而且我的站点每天有稳定的访问者。

And most importantly what would be the ideal cache time ? I would like to display the latest content from the twitter but the twitter api has the request limits.. And my site has solid visitors/day..

推荐答案

最干净的方法是使用 APC (备用PHP缓存)(如果已安装)。它具有内置的生存时间功能:

The cleanest way to do this would be to use APC (Alternative PHP Cache) if it installed. This has a built in "time to live" functionality:

if (apc_exists('twitter_result')) {
    $twitter_result = apc_fetch('twitter_result');
} else {
    $twitter_result = file_get_contents('http://twitter.com/...'); // or whatever your API call is
    apc_store('twitter_result', $twitter_result, 10 * 60); // store for 10 mins
}

10分钟的数据超时将是我的选择。这取决于Feed的更新频率...

A 10 minute timeout on the data would be my choice. This would vary depending on how frequently the feed is updated...

编辑没有安装APC,您可以使用一个非常简单的文件执行此操作:

Edit If you don't have APC installed, you could do this using a very simple file:

if (file_exists('twitter_result.data')) {
    $data = unserialize(file_get_contents('twitter_result.data'));
    if ($data['timestamp'] > time() - 10 * 60) {
        $twitter_result = $data['twitter_result'];
    }
}

if (!$twitter_result) { // cache doesn't exist or is older than 10 mins
    $twitter_result = file_get_contents('http://twitter.com/...'); // or whatever your API call is

    $data = array ('twitter_result' => $twitter_result, 'timestamp' => time());
    file_put_contents('twitter_result.data', serialize($data));
}

这篇关于如何缓存Twitter API的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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