2017-03-09 78 views
1

我通過控制器爲受保護的圖像提供服務,以便在需要時從公共視圖中禁用其中的一些圖像。因此我使用BinaryFileResponse,實際上直接從Nginx提供圖像。
這裏是控制器:在symfony3中加載私人圖像需要太長的時間

location /images-internal/ { 
    internal; 
    alias /home/vagrant/Sites/Symfony/app/; 
} 

路線中的routing.yml:其中X-加速重定向啓用nginx的配置的

public function getPictureAction(Request $request, $id) 
{ 
     $image = $this->getDoctrine() 
         ->getRepository('AppBundle:Images') 
         ->getOneById($id); 

     $dir = $this->get('kernel')->getRootDir() . '/'; 

     // Serving image by using Nginx's 'XSendfile' 
     $request->headers->set('X-Sendfile-Type', 'X-Accel-Redirect'); 
     $request->headers->set('X-Accel-Mapping', $dir . '=/images-internal/'); 
     BinaryFileResponse::trustXSendfileTypeHeader(); 

     $path = $dir . 'images/image.jpg'; 
     $response = new BinaryFileResponse($path); 

     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE); 

     return $response; 
} 

部分

picture_path: 
    path: /images/{id} 
    defaults: {_controller: AppBundle:Pages/Home:getPicture, _format: html} 
    methods: [GET] 
    options: 
     expose: true 

在枝條模板我加載圖像是這樣的:

<img src="{{ path('picture_path', {'id': imageId}) }}"> 

使用此設置,53KB圖像的平均加載時間大約爲700ms

出於測試目的,我用枝條的AssetExtension從公共Web目錄加載相同的圖像:

<img src="{{ asset('bundles/img/image.jpg') }}"> 

和負載時間正好是30毫秒

這是正常的,它需要很長時間通過控制器來加載圖像,還是我做錯了什麼?

回答

2

這取決於其他控制器的加載時間。我的意思是控制器返回常規響應,而不是二進制。如果他們的加載時間是700毫秒或更多,這是正常的。因爲只有Web服務器(nginx的)參與公共網頁目錄

加載圖像快。

通過控制器加載圖像涉及web-server(nginx),php,symfony。所以它需要與常規控制器相同的時間。

X-Accel-Redirect在這種情況下不會有太大的幫助,它通常用於大文件來釋放php進程。 Php進程發送這個頭並終止處理,然後nginx讀取併發送文件。

如果你想加快圖像加載嘗試安裝PHP opcache或寫純腳本的腳本沒有symfony,將處理圖像下載。

+0

感謝您的回覆。我期待在Profiler中的性能,並看到Symfony防火牆需要大約500ms。所以看起來防火牆出現了問題。 – rvaliev