gpt4 book ai didi

laravel - 了解 Laravel 缓存 : Cache facade and Redis

转载 作者:行者123 更新时间:2023-12-02 03:06:37 25 4
gpt4 key购买 nike

我是 Laravel 的新手。我已经对这个主题进行了研究,但我似乎找不到能为我解决问题的答案。

我知道 Laravel 的默认缓存驱动程序设置为 file,我可以更改它。它还具有一些工匠缓存命令,例如:

php artisan config:cache
php artisan route:cache

1) 即使 Laravel 有一些内置的命令和功能可以自动处理一些缓存(不明白到底是什么部分),我仍然必须在查询结果上手动使用 Cache facade ,对吧?

它不会自动执行,如果我想更改某些东西或其他东西,我只需要使用 Cache facade,对吧?

这是教程中的一个随机示例:

$posts = Cache::remember('index.posts', 30, function()
{return Post::with('comments', 'tags', 'author', 'seo')->whereHidden(0)->get();});

2) 当使用 Redis(带有 predis 包)作为缓存驱动时,我需要使用 Cache facade 还是 Redis facade,或者两者都用一些案例?或者我可以简单地在 Laravel 和服务器(Forge 上的 Digital Ocean droplet)中启用 Redis 并且不做任何其他事情吗?

我在 Laravel 文档中看到过类似的东西,使用 Cache facade:

Cache::store('redis')->put('bar', 'baz', 600);

我还看过一个使用 Redis facade 的教程:

use Illuminate\Support\Facades\Redis; 

Route::get('/', function () {
$visits = Redis::incr('visits');
return $visits;
});

我想不出什么是正确的做法。

最佳答案

常见:

它们都是缓存

它们都是用来减少时间成本的。

差异网:


配置和路由:

它属于应用。我们称之为应用程序缓存

php artisan config:cache
php artisan route:cache

这两条命令是缓存路由和配置。

路径:

They are always stored in bootstrap/cache/

运行

php artisan config:clear
php artisan route:clear

只清除bootstrap/cache/中的目录和文件。

它们是静态的。所以它们只有在您更改它们时才会更改。

好处

如果您更改它们,您需要手动清除缓存它们。

在你缓存这些路由和配置之后。

Laravel 不需要再次从文件中读取配置和路由,这会占用 IO 时间成本。


文件系统缓存和Redis缓存:

文件系统缓存和Redis缓存都是缓存。

但是,它们使用不同的驱动程序来存储数据,这意味着您在何处存储缓存数据

Filesystem PATH: If you are using filesystem driver. they are stored in storage/framework/cache/

Reids PATH: Datas store in redis by key-value.

你什么时候使用它们?

当你发现有很多请求到这段代码获取数据时。而且这些数据并没有那么快变化。

您可以使用缓存来存储它们,然后,下次对这个 api 的另一个请求。它只是从缓存中获取数据。如下所示:

$posts = Cache::remember('index.posts', 30, function()
{return Post::with('comments', 'tags', 'author', 'seo')->whereHidden(0)->get();});

第一个请求从数据库中获取帖子的数据,然后将这些数据存储在 30 秒后过期的缓存(Reids 或文件系统)中。

下一个请求仅通过缓存获取帖子的数据。他们不需要再次在数据库中搜索。

还有这个:

use Illuminate\Support\Facades\Redis; 

Route::get('/', function () {
$visits = Redis::incr('visits');
return $visits;
});

表示当人们请求localhost:8000/时,用户在redis中的访问次数增加(不需要存储在数据库中,需要更多时间),下次请求访问访问次数时,可以很快在redis中查到。

PS: Here use Redis Facade, then the datas are stored in redis.

If you are using redis as cache driver, Cache::remember() will store datas in redis too.

However, using Redis Facade, you can use many redis methods.

哪个更好?

我认为 redisfilesystem 好。

  1. 因为 redis 将数据存储在内存中,而文件系统存储在磁盘中。从内存中读取数据比磁盘更快

  2. 在 Redis 中操作数据比文件系统容易。例如 Redis 支持清除特定标签的所有缓存,但文件系统不能[因为文件系统通过加密 key 的名称存储缓存数据]。

  3. 对于分布式服务器,文件系统缓存不是个好主意。较低的缓存命中率。

老实说,还有其他驱动可以选择,比如mongodb

顺便说一句,我的英语不是很好,希望你能理解。

关于laravel - 了解 Laravel 缓存 : Cache facade and Redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com