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

Cache api (json) request to avoid repeating the request

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

require 'dotenv/load'
require 'faraday'

class OverviewController < ApplicationController

  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

回复:

{
    "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"
        },
...

目前效果很好。但是由于此 json 中的数据很少更改,并且有一项政策不要求 api 我想缓存我的结果。

我用 "faraday-http-cache" 尝试了不同的解决方案,但我无法让它工作。但我不想使用其他库。

我阅读了 "rails - Guides - caching" 部分,我想我需要 低级缓存 Rails.cache.fetch

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

编辑(在 Panic 发表评论后): 我试过了,但我需要更多帮助

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' 进行。我还收到错误消息“StatsClient.products 未被识别。

将控制器中的代码移至单独的 class(或模块)StatsClient。然后在你的控制器中:

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