3

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

  • 控制器HOME == 调用 => 模块app/application/modules/apis/controllers/c_$api == 加载库 => app/application/libraries/$api ==> 库返回响应到模块的控制器_X,控制器使用它拥有的数据调用视图

//注意:我的应用没有使用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个场景:home、query、result;在每个模块apis的控制器中,您认为在所有场景中为每个控制器实现缓存是一个好主意吗?例子:

    //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 模块控制器的控制器中,并具有相同的 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}可行(即使我认为它会)

4

1 回答 1

2

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

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

如果您担心处理器负载(在操作后缓存内容的唯一原因),那么最好的办法是查看VarnishCloudFront之类的东西。

于 2012-05-31T21:42:13.673 回答