缓存api(json)请求以避免重复请求

时间:2018-02-21 18:05:40

标签: ruby-on-rails ruby faraday

所以我创建了这个请求,它给了我作为json的响应。

{
    "type": "products",
    "version": "x.x.x",
    "data": {
        "Product 1": {
            "title": "xxx",
            "attributes": {
                "x"=1
            },
            "id": 22,
            "name": "Product 1"
        },
        "Product 2": {
            "title": "xXx",
            "attributes": {
                "x"=2
            },
            "id": 25,
            "name": "Product 2"
        },
...

响应:

Rails.cache.fetch

到目前为止这种方法很有效。但是因为这个json中的数据真的很少变化,并且有一个策略不能请求api,我想缓存我的结果。

我尝试了不同的解决方案" faraday-http-cache"但是我无法让它发挥作用。但我不想使用另一个lib。

我读了&#34; rails - 指南 - 缓存&#34;细分,我认为我需要低级缓存 require 'dotenv/load' require 'faraday' class StatsClient def api_key ENV["API_KEY"] end def url "https://example.com"+api_key end def index conn = Faraday.new(url, request: {open_timeout: 1, timeout: 1}) do |c| c.response :json, :content_type => /\bjson$/ c.adapter Faraday.default_adapter end response = conn.get url @hash = response.body['data'] end end class OverviewController < ApplicationController def index @hash = Rails.cache.fetch('something', expires_in: 15.minutes) do StatsClient.products end end end

如果有人可以帮助我,我会很高兴: - )

编辑(恐慌后评论): 我尝试了这个,但我还需要一些帮助

'something'

喜欢这个?实际上需要做什么 {{1}} 。此外,我收到错误,&#34; StatsClient.products无法识别。

1 个答案:

答案 0 :(得分:0)

将代码从控制器移动到单独的类(或模块)StatsClient中。然后在你的控制器中:

def index
  @hash = Rails.cache.fetch('something', expires_in: 15.minutes) do
    StatsClient.products
  end
end