Caching calls to an external API in a rails app

后端 未结 1 803
隐瞒了意图╮
隐瞒了意图╮ 2021-01-05 14:07

The rails app (4) calls an external API using HTTParty. The API is read only. Caching is required as the data does not change often (24h) and the API allow only a limited nu

相关标签:
1条回答
  • 2021-01-05 14:50

    It'll be something like this. Basically, the Rails.cache.fetch call will wrap your API call. It won't hit the API unless the cache has expired.

    class Results
    
      def get(url, params)
        Rails.cache.fetch([url, params], :expires => 1.hour) do
          HTTParty.get('url/to/api')
        end
      end
    
    end
    

    Be sure you have a cache set in your environment. Memcache works great for this sort of thing.

    0 讨论(0)
提交回复
热议问题