Laravel Caching



我有这个函数,它检索网站所有URL的页面标题:

function getTitle($url)
{
$pages = file_get_contents($url);
$title = preg_match('/<title[^>]*>(.*?)</title>/ims', $pages, $match) ? $match[1] : null;
return $title;
}

然后我做了一个循环,它运行得很好(好结果(,但我想使用"file_get_contents"的缓存,所以我做了:

function getTitle($url)
{
$pages = cache()->Cache::remember('key', now()->addDay(), fn() => file_get_contents($url));
$title = preg_match('/<title[^>]*>(.*?)</title>/ims', $pages, $match) ? $match[1] : null;
return $title;
}

一方面缓存工作正常(现在超高速(,但另一方面,所有标题都是一样的(糟糕的结果(。

我的逻辑错在哪里?这是我第一次使用缓存。

文件依赖于$url,并且您将独立于它缓存file_get_contents,因此无论$url值如何,都将使用相同的缓存。

使缓存依赖于url。但我不知道这是不是你想要的性能升级。

$pages = cache()->Cache::remember('key-'.$url, now()->addDay(), fn() => file_get_contents($url))

您应该延长缓存的使用时间并在创建或修改时刷新,或者让cron每天刷新缓存。

最新更新