php - 定义好的缓存场景

标签 php codeigniter caching apc

我需要知道我是否可以改进从我的 CodeIgniter 应用程序内部缓存我的 api 调用的方式。我现在这样做的方式是这样的,采用 hmvc 模式:

  • Controller HOME == 调用 => 模块 app/application/modules/apis/controllers/c_$api == 加载库 => app/application/libraries/$api ==> 库返回响应给模块的controller_X, Controller 用它拥有的数据调用 View

//注意:我的应用没有使用twitter api,而是其他的

apis 模块内部是所有 apc 缓存发生的地方,如下所示:

    // Load up drivers
    $this->load->library('driver');
    $this->load->driver('cache', array('adapter' => 'apc'));

    // Get Tweets from Cache
    $tweets = $this->cache->get('my_tweets');

    if ( ! $tweets)
    {
        // No tweets in the cache, so get new ones.
        $url = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=gaker&count=5';

        $tweets = json_decode(file_get_contents($url));
        $this->cache->save('my_tweets',$tweets, 300);
    }

    return $tweets;

如本文所述:http://www.gregaker.net/2011/feb/12/codeigniter-reactors-caching-drivers/

所以我想知道:

  1. 有 3 个场景:主页、查询、结果;在每个模块 apis 的 Controller 中,您认为为所有场景的每个 Controller 实现缓存是个好主意吗?示例:

    //for each api1, api2 ... apiX, apply this:
    
    //home
    $this->cache->save('api_home',$api_home, 300);
    
    //query
    $this->cache->save("api_$query", $api_{$query}, 300); // I don't know for sure if $api_{$query} works or not, so don't hang me because I haven't tried it.
    
    //result
    $this->cache->save("api_$queryId", $api_{$queryId}, 300);
    
  2. 即使我缓存了 api 调用,您认为我应该将结果缓存在调用 api 模块 Controller 的 Controller 中,具有相同的 3 个场景(主页、查询和结果)吗?像这样:

    //modules/{home,fetch,article}/controllers/{home,fetch,article}.php
    
    //home
    $homeData['latest'][$api]   = modules::run("apis/c_$api/data", array('action'=>'topRated'));
    $this->cache->save('home_data', $home_data, 300);
    
    //query
    $searchResults[$api] = modules::run("apis/c_$api/data", $parameters);
    $this->cache->save("search_results_$query", $search_results_{$query}, 300);
    
    //article page
    $result = modules::run("apis/c_$api/data", $parameters);
    $this->cache->save("$api_article_$id", ${$api}_article_{$id}, 300);
    

那么,你怎么看?上面提到的是一个好的做法,还是一个非常愚蠢的做法?

//注意,建议的缓存想法没有经过测试...所以,我不知道 ${$api}_article_{$id} 是否有效(尽管我假设它会)

最佳答案

恕我直言,如果不需要实时数据,缓存 api 结果是个好主意。如果您不在乎一个小时内看不到新数据,那么一定要将其缓存一个小时。因此,对于您的第一个问题,您只需要问自己:“我的应用程序的内容需要多新鲜?”并相应地实现缓存。

对于第二个问题:如果仅以简单的方式进行操作,我认为缓存内容没有多大值(value)。那时您正在用完缓存中的空间并且没有获得很多值(value)。但是,如果有数据库或使用该数据进行的其他 api 调用,那么是的,它们应该使用与上述类似的技术进行缓存。

如果您担心处理器负载(操作后缓存内容的唯一原因),您最好的办法是查看类似 Varnish 的内容或 CloudFront .

关于php - 定义好的缓存场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739226/

相关文章:

javascript - 在特定 URL 目录 (htaccess) 上运行 javascript 函数

PHP 计算对象属性出现次数

Sharepoint - 如何启用无服务器访问的缓存?

c# - 使用 HttpRuntime.Cache 的问题

php - 导航栏 Logo 下降且按钮未正确折叠

php - 如何使用PHP通过HTTP PUT接收文件

mysql - 如何在 CodeIgniter 中选择特定数字作为查询中的列值

php - 使用ajax codeigniter检查用户名和密码是否匹配

php - 从 mysql 数据库查询中使用 php 时加快 csv 导出

http - 如何确保我的用户正在下载我的 S3 文件的新版本?