kielabokkie / uber-cache
以特定持续时间为条件检索和存储缓存
v1.0.0
2021-03-05 11:20 UTC
Requires
- php: ^7.4|^8.0
- nesbot/carbon: ^2.45
Requires (Dev)
- nunomaduro/larastan: ^0.7.0
- orchestra/testbench: ^4.0|^5.0|^6.0
- phpunit/phpunit: ^9.5
- rachidlaasri/travel: ^1.0
- squizlabs/php_codesniffer: ^3.5
README
UberCache for Laravel 与 Laravel 的 检索和存储 缓存功能非常相似。区别在于,一旦 Laravel 的缓存过期,并且新数据的检索失败,你将没有任何数据。这就是 UberCache 发挥作用的地方,因为它允许你在检索新数据失败时重用旧缓存。
赞助我
如果你觉得这个包很有用,或者它以某种方式带来了快乐,请考虑赞助我。
要求
- PHP >= 7.4
- Laravel 6.x 及更高版本
安装
通过 composer 安装包
composer require kielabokkie/uber-cache
TLDR
// data is fetched from the external API and cached for 1 minute $todo = UberCache::remember('key', now()->addMinute(), now()->addHour(), function () { return Http::get('https://jsonplaceholder.typicode.com/todos/1')->json(); }); dump($todo); /** { id: 1, title: "delectus aut autem", completed: false } */ // -- 5 minutes later -- // cache is expired so should fetch from API but API is down $todo = UberCache::remember('key', now()->addMinute(), now()->addHour(), function () { throw new \Exception('API error'); }); // the todo still returns the previously expired cache dump($todo); /** { id: 1, title: "delectus aut autem", completed: false } */ // -- 2 hours later -- // cache is expired and max cache time also expired but API is still down $todo = UberCache::remember('key', now()->addMinute(), now()->addHour(), function () { throw new \Exception('API error'); }); // an UberCacheException is thrown
使用方法
如前所述,UberCache 提供了一个与 Laravel 的 remember
缓存函数非常相似的功能。让我们先看看这个功能的第一个示例
$value = Cache::remember('todos', now()->addMinute(), function () { return Http::get('https://jsonplaceholder.typicode.com/todos/1')->json(); });
如你所见,它接受 3 个参数:缓存键、缓存中值的生命周期以及负责检索数据的回调函数。
现在让我们看看 UberCache 的 remember 函数,它在回调函数调用之前接受一个额外的参数 maxTtl
。这个参数用于设置缓存允许使用的最大时间。
$value = UberCache::remember('todos', now()->addMinute(), now()->addHour(), function () { return Http::get('https://jsonplaceholder.typicode.com/todos/1')->json(); });
很明显,它与 Laravel 的 remember 函数几乎完全相同,但多亏了 maxTtl
参数,我们的缓存变得稍微智能一些。上面的示例将缓存获取的待办事项 1 分钟。如果这个函数在超过 1 分钟后再次被调用,则缓存过期,因此 API 调用将再次执行。如果 API 调用由于任何原因失败,比如它暂时关闭,UberCache 将恢复旧的缓存值并继续执行而不会中断。
如果 API 调用持续失败,并且不能在 maxTtl
设置的时间内获取新数据,则将抛出一个异常。这是为了确保你不会永远在没有意识到的情况下使用旧缓存数据。