PHP 中的 5 分钟文件缓存 [英] 5-minute file cache in PHP

查看:37
本文介绍了PHP 中的 5 分钟文件缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题:下载 PHP 文件的最佳方法是什么,但前提是本地版本已在 5 分钟前下载?

I have a very simple question: what is the best way to download a file in PHP but only if a local version has been downloaded more than 5 minute ago?

在我的实际情况中,我想从我目前使用的远程托管的 csv 文件中获取数据

In my actual case I would like to get data from a remotely hosted csv file, for which I currently use

$file = file_get_contents($url);

没有任何本地副本或缓存.将其转换为缓存版本的最简单方法是什么,最终结果不会改变($file 保持不变),但如果它在不久前(比如 5 分钟)被获取,则它使用本地副本?

without any local copy or caching. What is the simplest way to convert this into a cached version, where the end result doesn't change ($file stays the same), but it uses a local copy if it’s been fetched not so long ago (say 5 minute)?

推荐答案

使用本地缓存文件,使用前只需检查文件的存在和修改时间即可.例如,如果 $cache_file 是本地缓存文件名:

Use a local cache file, and just check the existence and modification time on the file before you use it. For example, if $cache_file is a local cache filename:

if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 5 ))) {
   // Cache file is less than five minutes old. 
   // Don't bother refreshing, just use the file as-is.
   $file = file_get_contents($cache_file);
} else {
   // Our cache is out-of-date, so load the data from our remote server,
   // and also save it over our cache for next time.
   $file = file_get_contents($url);
   file_put_contents($cache_file, $file, LOCK_EX);
}

(未经测试,但基于我目前使用的代码.)

(Untested, but based on code I use at the moment.)

无论通过这段代码,$file 最终都会作为您需要的数据,如果它是新鲜的,它将使用缓存,或者从远程服务器获取数据并刷新缓存,如果不是.

Either way through this code, $file ends up as the data you need, and it'll either use the cache if it's fresh, or grab the data from the remote server and refresh the cache if not.

自从我写了上面的内容后,我对文件锁定有了更多的了解.如果您担心此处的文件锁定,可能值得阅读此答案.

I understand a bit more about file locking since I wrote the above. It might be worth having a read of this answer if you're concerned about the file locking here.

如果您担心锁定和并发访问,我想说最干净的解决方案是将 file_put_contents 放到 临时 文件中,然后 rename() 它在 $cache_file 之上,这应该是一个原子操作,即 $cache_file 要么是旧内容,要么是完整的新内容,永远不会写到一半.

If you're concerned about locking and concurrent access, I'd say the cleanest solution would be to file_put_contents to a temporary file, then rename() it over $cache_file, which should be an atomic operation, i.e. the $cache_file will either be the old contents or the full new contents, never halfway written.

这篇关于PHP 中的 5 分钟文件缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆