【问题标题】:how to cache the twitter api result?如何缓存 twitter api 结果?
【发布时间】:2012-10-02 17:04:19
【问题描述】:

我想缓存 twitter api 结果的结果并显示给用户..

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

我正在考虑根据时间限制将结果写入文件.. 可以吗?还是应该使用其他方法?

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

【问题讨论】:

    标签: php caching twitter


    【解决方案1】:

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

    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 分钟的数据超时将是我的选择。这将根据提要的更新频率而有所不同...


    编辑如果您没有安装 APC,您可以使用一个非常简单的文件来完成:

    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));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多