【问题标题】:Cache api (json) request to avoid repeating the request缓存api(json)请求,避免重复请求
【发布时间】:2018-02-21 18:05:40
【问题描述】:

所以我创建了这个请求,它给了我一个 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 - 缓存”部分,我认为我需要低级缓存 Rails.cache.fetch

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

编辑(在恐慌的评论之后): 我试过了,但我需要更多帮助

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 的错误。

【问题讨论】:

    标签: ruby-on-rails ruby faraday


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答。我尝试了您的解决方案,但无法使其正常工作。我编辑了我的问题。
    • @mrdmr 在您的代码中,您需要将def index 替换为def products,将StatsClient.products 替换为StatsClient.new.products,并将@hash = response.body['data'] 替换为response.body['data']
    猜你喜欢
    • 2016-10-15
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 2022-01-23
    • 2015-01-24
    相关资源
    最近更新 更多