【问题标题】:Google API request every 30 seconds每 30 秒发出一次 Google API 请求
【发布时间】:2014-03-26 16:56:23
【问题描述】:

我正在使用 Live Reporting Google API 来检索活跃用户并在移动应用程序中显示数据。在我的应用程序中,我想向服务器上的 PHP 脚本发出 HTTP 请求,该脚本应该返回结果。 但是,我在 Google 文档上看到,使用 API 请求数据的频率最好不要超过 30 秒。 我不喜欢使用繁重的方式,例如将值存储在数据库中的 cron 作业。所以我想知道是否有办法缓存我的 PHP 脚本的内容,它只在缓存过期时才执行 API 请求。 有没有类似的方法可以做到这一点?

【问题讨论】:

  • 如果您没有在页面请求中执行对 API 的调用,那么您将不得不使用 CRON - (据我所知)无法触发缓存数据过期等事件。
  • @Kryten 是的,API 调用应该在页面请求上执行,但前提是缓存超过 30 秒
  • 那么它应该很简单,可以检查每个页面请求的缓存年龄并决定是否要进行 API 调用。使用文件系统或数据库保存最后一次 API 调用的日期/时间,并在每次页面加载时检查它 - 如果您只是获取时间戳值,开销应该不会太多。
  • @Kryten 的重点是我既不想创建值也不想创建数据库字段来存储这个
  • 如果您想针对每个用户执行此操作,您可以将值存储在 cookie 中,但您最终可能会比每 30 秒更频繁地调用 API。

标签: php caching google-api-php-client


【解决方案1】:

另一种方法是自己实现一个非常简单的缓存。

$googleApiRequestUrlWithParameter; //This is the full url of you request
$googleApiResponse = NULL; //This is the response by the API

//checking if the response is present in our cache
$cacheResponse = $datacache[$googleApiRequestUrlWithParameter];
if(isset($cacheResponse)) {
  //check $cacheResponse[0] for find out the age of the cached data (30s or whatever you like
  if(mktime() - $cacheResponse[0] < 30) {
    //if the timing is good
    $googleApiResponse = $cacheResponse[1];
  } else {
    //otherwise remove it from your "cache"
    unset($datacache[$googleApiRequestUrlWithParameter]);
  }
}

//if you do no have the response
if(!isset($googleApiResponse)) {
   //make the call to google api and put the response in $googleApiResponse then
   $datacache[] = array($googleApiRequestUrlWithParameter => array(mktime(), $googleApiResponse)
}

如果您的数据与用户会话相关,您可以将 $datacahe 存储到 $_SESSION http://www.php.net/manual/it/reserved.variables.session.php

否则定义 $datacache = array();作为一个全局变量。

【讨论】:

    【解决方案2】:

    在 PHP 中有很多缓存方法,在 PHP 中管理缓存的简单/历史方法是使用 APC http://www.php.net/manual/book.apc.php

    也许我没有正确理解你的问题。

    【讨论】:

    • 我打算用这个写一些代码,同时谢谢你
    • 在我的共享主机上,APC 不可用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多