版本控制10/laravel-permanent-cache

使用 Laravel 永久缓存,您可以永久缓存耗时的操作并在后台更新它们,这样您的用户就不必等待了!

v0.3.16 2024-05-15 18:59 UTC

README

Total Downloads Tests PHPStan GitHub release (latest by date) Packagist PHP Version Support Latest Version on Packagist

此包旨在为使用重型 Eloquent 模型、数据库查询或其他长时间运行任务的任务提供使用永久缓存的功能。永久缓存会在后台通过计划任务或监听事件自动更新,这样就不会对用户的请求造成伤害。

其用途主要是用于需要返回复杂数据或 HTML 的重型任务,这些数据不需要实时更新,但仍需定期更新。例如,外部 API 调用可能需要几秒钟才能处理,或其他 1+ 秒钟的任务。

安装

您可以通过 composer 安装此包

composer require vormkracht10/laravel-permanent-cache

可选,发布配置文件以更改默认配置

php artisan vendor:publish --provider="Vormkracht10\PermanentCache\PermanentCacheServiceProvider"

默认配置选项

<?php

return [
    // Default cache driver to use for permanent cache
    'driver' => env('PERMANENT_CACHE_DRIVER', 'file'),

    // Option for cached components to add markers around output
    'components' => [
        // Add markers around the rendered value of Cached Components,
        // this helps to identify the cached value in the rendered HTML.

        // Which is useful for debugging and testing, but also for updating
        // the cached value inside another cache when using nested caches
        'markers' => [
            'enabled' => env('PERMANENT_CACHE_MARKERS_ENABLED', true),
            'hash' => env('PERMANENT_CACHE_MARKERS_HASH', env('APP_ENV') === 'production'),
        ],
    ],
];

使用方法

您必须将您创建的所有缓存注册到 PermanentCache::caches 门面。我们建议将其放在 AppServiceProviderboot 方法中。

您可以通过多种方式注册缓存

use \Vormkracht10\PermanentCache\Facades\PermanentCache;

# When you don't need parameters per class, you can use direct parameters or an array:

# Without an array
PermanentCache::caches(
    LongRunningTask::class,
    LongerRunningTask::class,
);

# Passing an array
$caches = [
    LongRunningTask::class,
    LongerRunningTask::class,
];

PermanentCache::caches($caches);

# Specifying parameters per class
PermanentCache::caches([
    LongRunningTask::class => ['type' => 'long'],
    LongerRunningTask::class => ['type' => 'longer'],
]);

# As a multi-dimensional array when you need to use the same class multiple times, but with different parameters
PermanentCache::caches(
    [LongRunningTask::class => ['type' => 'long']],
    [LongRunningTask::class => ['type' => 'longer']],
);

永久缓存的定义

永久缓存可能是一个运行时间超过您希望用户等待的任务。这就是为什么您需要将其在后台运行,定期使用调度器或当事件发生时以及使用 Laravel 的队列系统进行更新。

您可以使用类上的 $store 属性定义缓存存储和键,遵循以下定义:cache-driver:key,例如:redis:a-unique-cache-key

use Vormkracht10\PermanentCache\Cached;

class LongRunningTask extends Cached
{
    protected $store = 'redis:a-unique-cache-key';

    public function run(): string
    {
        return "I'm executing a long running task!";
    }
}

缓存可以监听事件

如果您只想监听单个事件,您可以在 run 方法中指定事件类型提示

use Vormkracht10\PermanentCache\Cached;

class LongRunningTaskListeningForEvents extends Cached
{
    protected $store = 'redis:unique-cache-key';

    public function run(TestEvent $event): string
    {
        return "I'm executing because of {$event->name}!";
    }
}

监听多个事件

永久缓存可以通过在 $events 属性上使用数组来监听多个事件进行更新

use Vormkracht10\PermanentCache\Cached;

class LongRunningTaskListeningForEvents extends Cached
{
    protected $store = 'redis:unique-cache-key';

    protected $events = [
        TestEvent::class,
        OtherEvent::class,
    ];
    
    /** @param TestEvent|OtherEvent $event */
    public function run($event): string
    {
        return "I'm executing because of {$event->name}!";
    }
}

缓存可以定期通过调度器更新

永久缓存可以通过添加 schedule 方法或具有 cron 字符串的 $expression 属性来使用调度器进行更新(同时监听事件)

请注意,如果您决定监听事件和调度您的缓存,不要在 run 方法中尝试接受 $event 参数,因为当计划运行时,这不会提供给您。

use Vormkracht10\PermanentCache\Cached;
use Vormkracht10\PermanentCache\Scheduled;

class LongRunningTaskExecutedPeriodicallyOrWhenAnEventHappens extends Cached implements Scheduled
{
    protected $store = 'redis:unique-cache-key';

    protected $events = [
        TestEvent::class,
    ];

    // Use cron expression
    protected $expression = '* * * * *'; // run every minute

    public function run(): string
    {
        return "I'm executing because of {$event->name} or a scheduled run!";
    }

    // Or use the `schedule` method using a callback
    public static function schedule($callback)
    {
        return $callback->everyHour();
    }
}

缓存可以通过队列分发进行更新

永久缓存可以通过实现 Laravel 的 ShouldQueue 接口并(可选)指定队列来通过队列分发进行更新

use Illuminate\Contracts\Queue\ShouldQueue;
use Vormkracht10\PermanentCache\Cached;
use Vormkracht10\PermanentCache\Scheduled;

class LongRunningTaskExecutedPeriodicallyOrWhenAnEventHappensDispatchedOnTheQueue extends Cached implements ShouldQueue
{
    protected $store = 'redis:unique-cache-key';

    public $queue = 'execute-on-this-queue';

    public function run(TestEvent $event): string
    {
        return "I'm dispatching for execution on the queue because of {$event->name}!";
    }
}

特性:缓存的 Blade 组件

一个超级实用的特性是“缓存组件”,这些是包含长期运行任务(您不希望用户等待完成)的 Blade 组件。因此,当需要时,您可以在后台执行 Blade 组件,使用调度器或队列,同时可选地监听导致永久缓存更新的事件。

use Illuminate\Contracts\Queue\ShouldQueue;
use Vormkracht10\PermanentCache\CachedComponent;
use Vormkracht10\PermanentCache\Scheduled;

class HeavyComponent extends CachedComponent implements Scheduled, ShouldQueue
{
    protected $store = 'redis:unique-cache-key';

    protected $events = [
        TestEvent::class,
    ];

    public function render()
    {
        return view('components.heavy-component');
    }

    public static function schedule($callback)
    {
        return $callback->everyHour();
    }
}

当加载您的 Blade 组件时,它将始终使用缓存而不是执行长时间的任务

<x-long-during-task />

手动更新永久缓存

手动更新永久缓存非常简单。只需使用静态 update 方法。这将自动运行或排队执行任务

LongTaskInPermanentCache::update(['parameter' => 'value']);

或者一次性更新所有缓存

use Vormkracht10\PermanentCache\Facades\PermanentCache;

PermanentCache::update();

更新永久缓存时的事件

当永久缓存被更新时,会触发这些事件

# Before updating the cache
use Vormkracht10\PermanentCache\Events\PermanentCacheUpdating;

# After the cache has been updated
use Vormkracht10\PermanentCache\Events\PermanentCacheUpdated;

控制台命令

此包包含Artisan命令,用于实现永久缓存时优化DX

# Update all caches that match namespace using the optional filter
php artisan permanent-cache:update --filter=

# Show status overview of all registered caches including cached status, cache size, last updated at and scheduled update frequency
php artisan permanent-cache:status --parameters --filter=
关于工作队列和队列的更多信息

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件获取更多信息。