简体   繁体   English

在 Laravel 中缓存图像的最有效方法

[英]Most efficient way to cache images in Laravel

I am developing a Laravel application in which I need to display images from Instagram's CDN and thought it would be a good idea to cache these instead of constantly having to query the CDN.我正在开发一个 Laravel 应用程序,我需要在其中显示来自 Instagram 的 CDN 的图像,并认为缓存这些图像而不是不断地查询 CDN 是个好主意。

I found Intervention Image Cache as the only option for my requirements.我发现干预图像缓存是满足我要求的唯一选择。 I wrote a simple route that involved passing part of the CDN url and then calling a controller to cache the image.我写了一个简单的路由,涉及传递部分 CDN url,然后调用控制器来缓存图像。 I must mention I'm using FileSystem storage as the cache driver.我必须提到我使用 FileSystem 存储作为缓存驱动程序。

routes/web.php

Route::get('/img/{code}/', 'PostController@setImageCached');

app/Http/Controllers/PostController.php

public function setImageCached($code) {
        $cdn_image = $this->getImage($code);
        $img = Image::cache(function($img) use($cdn_image){
            return $img->make($cdn_image);
        }, 10);
        return Response::make($img, 200, array('Content-Type' => 'image/jpeg'));
    }

And whilst it works, it's painfully slow, almost three times slower than actually getting the image directly from the CDN, so either I'm using the library wrong or it's not caching the images.虽然它可以工作,但它非常缓慢,几乎比直接从 CDN 获取图像慢三倍,所以要么我使用的库错误,要么它没有缓存图像。

Is there a better approach to caching images from a CDN so that my application does not have to constantly query Instagram's CDN?是否有更好的方法从 CDN 缓存图像,以便我的应用程序不必不断查询 Instagram 的 CDN?

You could try the built-in Laravel caching mechanism.你可以试试内置的 Laravel 缓存机制。 Not sure how the library you're using works so this may be a more reliable approach.不确定您使用的库是如何工作的,因此这可能是一种更可靠的方法。

public function setImageCached($code) {
        $cdn_image = $this->getImage($code);
        $img = Cache::remember('image_'.$cdn_image, 10, function () use ($cdn_image) {  
           return file_get_contents($cdn_image);
        });
        return Response::make($img, 200, array('Content-Type' => 'image/jpeg'));
    }

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

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