如何在调用新数据之前缓存服务器调用并测试缓存过期? [英] How to cache a server call and test for cache expiration prior to calling for new data?

查看:42
本文介绍了如何在调用新数据之前缓存服务器调用并测试缓存过期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此脚本来检索Google网络字体列表.如何缓存结果并使用该结果确定是从缓存还是从服务器调用中加载?

I'm using this script to retrieve a list of Google web fonts. How can I cache the results and use that to determine whether to load from cache or server call?

$googleFontsArray = array();
$googleFontsArrayContents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents);

foreach($googleFontsArrayContentsArr as $font)
{
    $googleFontsArray[$font['font-name']] = $font['font-name'];
}

推荐答案

您可以对序列化数据进行本地复制,并且每小时仅更新一次文件:

You could make a local copy of the serialized data and only update the file every hour:

$cache_file = 'font_cache';

$update_cache = false;
$source = $cache_file;
if(!file_exists($cache_file) || time() - filemtime($cache_file) >= 3600) // Cache for an hour
{
     $source = 'http://phat-reaction.com/googlefonts.php?format=php';
     $update_cache = true;
}

$googleFontsArray = array();
$googleFontsArrayContents = file_get_contents($source);
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents);

foreach($googleFontsArrayContentsArr as $font)
{
    $googleFontsArray[$font['font-name']] = $font['font-name'];
}

if($update_cache)
{
    file_put_contents($cache_file, $googleFontsArrayContents);
}

这篇关于如何在调用新数据之前缓存服务器调用并测试缓存过期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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