如何在没有数据库的情况下每5分钟保存一次Php变量


How to save Php variable every 5 minutes without database

在我的网站上有一个php函数func1(),它从其他资源中获取一些信息。运行此函数的成本非常高。

我希望当Visitor1访问我的网站时,执行这个func1(),并将值存储在文本文件(或其他文件,但不是数据库)中的$variable1=func1();中。

然后开始5分钟的时间间隔,在这个时间间隔内,Visitor2访问我的网站时,他从文本文件中获得值,而不调用函数func1()

Visitor3在20分钟后出现时,应再次使用该功能,并将新值存储5分钟。

如何制作?一个小的工作例子会很好。

将其存储在文件中,并使用filemtime()检查文件的时间戳。如果太旧,请刷新。

$maxage = 1200; // 20 minutes...
// If the file already exists and is older than the max age
// or doesn't exist yet...
if (!file_exists("file.txt") || (file_exists("file.txt") && filemtime("file.txt") < (time() - $maxage))) {
  // Write a new value with file_put_contents()
  $value = func1();
  file_put_contents("file.txt", $value);
}
else {
  // Otherwise read the value from the file...
  $value = file_get_contents("file.txt");
}

注意:已经有了专用的缓存系统,但如果您只需要担心这一个值,那么这是一个简单的缓存方法。

您试图实现的功能称为缓存。您在这里看到的其他一些答案描述了最简单的缓存:到文件。根据数据的大小、应用程序的需求等,还有许多其他缓存选项。

以下是一些缓存存储选项:

  • 文件
  • 数据库/SQLite(是的,您可以缓存到数据库)
  • MemCached
  • APC
  • XCache

还有很多东西可以缓存。以下是一些:

  • 纯文本/HTML
  • 序列化数据,如PHP对象
  • 函数调用输出
  • 完成页面

对于一种简单但可配置的缓存方式,可以使用Zend Framework中的Zend_cache组件。这可以单独使用,而无需使用本教程中描述的整个框架。

我看到有人说使用会话。这不是您想要的,因为会话仅对当前用户可用。

以下是使用Zend_Cache:的示例

include ‘library/Zend/Cache.php’;
// Unique cache tag
$cache_tag = "myFunction_Output";
// Lifetime set to 300 seconds = 5 minutes
$frontendOptions = array(
   ‘lifetime’ => 300,
   ‘automatic_serialization’ => true
);
$backendOptions = array(
    ‘cache_dir’ => ‘tmp/’
);
// Create cache object 
$cache = Zend_Cache::factory(‘Core’, ‘File’, $frontendOptions, $backendOptions);
// Try to get data from cache
if(!($data = $cache->load($cache_tag)))
{
    // Not found in cache, call function and save it
    $data = myExpensiveFunction();
    $cache->save($data, $cache_tag);
}
else
{
    // Found data in cache, check it out
    var_dump($data);
}

在文本文件中。最古老的节约方式(几乎)。或者做一个cronjob,在访问时每5分钟独立运行一次带有该函数的脚本。

使用缓存,例如APC!

如果资源真的很大,这可能不是最好的选择,文件可能会更好。

查看:

  • apc_store
  • apc_fetch

祝你好运!