开发者

Caching dynamic images in Rails

I am using the rmagick gem for generating dynamic images from a controller. The controller takes an id as a param, does a look up on a model, writes text over an existing image, and outputs it.

I have run some benchmarks comparing generating it for every request versus writing to disk and using send_data to output it if it already exists. I haven't noticed much of a difference in requests/secon开发者_JAVA技巧d between these two methods.

Is there a best practice for caching the image or writing it to disk instead of generating it dynamically for every request? Once generated, these images would remain mostly static but I would also like the option to re-generate it after a certain time interval.


The best practice is to cache generated images and allow the webserver to serve them.

Use a webserver such as Apache or Nginx in front of your Rails app, and make sure you write the image to a location where the webserver can serve it. So if your Rails route evaluates to /dynamic_images/3.png (which calls dynamic_images_controller action show with id=3 and format=png), write that image into public/dynamic_images/3.png and use send_file in the controller to send it.

The next time that file is requested (/dynamic_images/3.png), the webserver will gladly serve it (cached) and the Rails app will never get hit.

For advanced needs, like re-generating the images, and cleaning up your controller code, have a look at the paperclip gem.


Just an idea (never tried): why not store images (especially the ones that are dynamically generated) with memache?

Rails.cache.write("MY_IMAGE", image)


You should put cached images into such a directory from where they will be served by the web server. You don't want to use send_data for this - that's too slow. Also, you'll probably want to ignore that directory in your VCS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜