简体   繁体   English

在 Laravel 中使用 Redis 缓存图像?

[英]Cache image with Redis in Laravel?

I'm currently using Redis to serve cached content in my Laravel application.我目前正在使用 Redis 在我的 Laravel 应用程序中提供缓存内容。 I've noticed using it with the Cache Facade is slower than with native Redis commands and other people have noticed too .我注意到将它与 Cache Facade 一起使用比使用本机 Redis 命令要慢, 其他人也注意到了 I'd like to replace this snippet with one that implements the Redis facade.我想用实现 Redis 外观的代码段替换此代码段。

public function setImageCached(Request $request)
{
    $img = Cache::remember('image_'.$request->url, 6000, function () use ($request) {
        return file_get_contents($request->url);
    });
    
    return Response::make($img, 200, array('Content-Type' => 'image/jpeg'));
}

Forming this answer off the comments, so question may need to be updated to match.根据评论形成此答案,因此可能需要更新问题以匹配。

To use different cache drivers in different contexts, you can define a default cache driver (redis would be best for this) and then use a separate store for files with the following要在不同的上下文中使用不同的缓存驱动程序,您可以定义一个默认的缓存驱动程序(redis 最适合此),然后为具有以下内容的文件使用单独的存储

Cache::store('file')->remember('image_'.$request->url, 6000, function () use ($request) {
        return file_get_contents($request->url);
});

This will use the filesystem driver to cache, well, files, which is a better solution that redis for this use.这将使用文件系统驱动程序来缓存文件,这是 redis 用于此用途的更好的解决方案。

One thing to note, as you have also discovered, is that Laravel doesn't clean up expired cache files.需要注意的一件事,正如您还发现的,Laravel 不会清理过期的缓存文件。 There is a package that can handle this for you arifhp86/laravel-clear-expired-cache-file which gives you an artisan command有一个软件包可以为您处理此问题arifhp86/laravel-clear-expired-cache-file它为您提供了一个 artisan 命令

php artisan cache:clear-expired

You can schedule this to run as often as you wish您可以安排它按您希望的频率运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM