Server side caching

Our webapp will make API calls to retrieve images. These images can be cached for a reasonable period of time, as indicated in terms, so we do not need to click on other site servers with every page request.

I'm new to caching, but I just watched some Railscasts about some different methods. page caching, fragment caching, dynamic page caching. All of them help to reduce the number of requests and, consequently, the speed of the my application .

But how can I "cache" images from another site on my servers? What is the right way to do this? Are there any features for this purpose?

My attempt

- add a timestamp cache_outdates_atto my model Imageand set it to one month in the future. Whenever an image is loaded again, it updates the timestamp.

Then I will add a cronjob to check for obsolete images and then delete them.

+4
source share
3 answers

Good question. If you look at the problem outside the box, this is pretty easy.

When receiving a third-party server image, simply copy these images and place them on your server or in the CDN. And use it. To do this, you need to configure some method, for example

# app/model/image.rb
def image_link(name_of_image)
 if File.exist? "/some/#{name_of_image}.jpg"
    path = "/some/#{name_of_image}.jpg"
 else
  external_image_link = external_api_call(name_of_image)
  DownloadImageWorker.perform_async(external_image_link) // perform it asynchronously
  external_image_link 
 end
+3
source

Rails . HTTP-, , Squid. Squid, .

, - URL-, , cache.example.com URL-, . DNS, *.cache.example.com Squid-. Squid , .

, , Squid. , , , Rails.

+1

. , ​​, , .

, .

Photo, external_url etag, ( ).

, image_url, API, .

      photo = Photo.find_or_initialize_by(external_url: image_url)
      img_responce = Faraday.get do |req|
        req.url image_url
        if photo.etag
          req.headers['If-None-Match'] = photo.etag
        end
      end

      case img_responce.status
      when 200
        # This mean, image changes (or new)
        photo.update external_url: image_url,
                     etag: img_responce.headers['etag'],
                     image: StringIO.new(img_responce.body)
      when 304
        # This mean, image doesn't change
      end 
0

Source: https://habr.com/ru/post/1534455/


All Articles