【问题标题】:Rails: Cache API request with TyphoeusRails:使用 Typhoeus 缓存 API 请求
【发布时间】:2021-07-23 13:26:36
【问题描述】:

如何在 Rails 中使用 Typhoeus gem 缓存 api 请求?经过 2 小时的尝试,我放弃了自己尝试。

我有以下代码:

            hydra = Typhoeus::Hydra.new
            requests = urls.map do |url|
                request = Typhoeus::Request.new(url, followlocation: true)
                hydra.queue(request)
                request
            end
            hydra.run

他们的文档说“Typhoeus 包含对缓存的内置支持。在以下示例中,如果缓存命中,缓存的对象将传递给请求对象的 on_complete 处理程序。”

class Cache
  def initialize
    @memory = {}
  end

  def get(request)
    @memory[request]
  end

  def set(request, response)
    @memory[request] = response
  end
end

Typhoeus::Config.cache = Cache.new

Typhoeus.get("www.example.com").cached?
#=> false
Typhoeus.get("www.example.com").cached?
#=> true

但我不明白将这段代码放在哪里。

【问题讨论】:

    标签: ruby-on-rails api caching request


    【解决方案1】:

    创建一个初始化器来设置缓存。类似于:(config/initializers/typhoeus.rb)

    redis = Redis.new(url: "your redis url")
    Typhoeus::Config.cache = Typhoeus::Cache::Redis.new(redis, default_ttl: 60)
    

    然后在您的请求中您可以添加缓存相关选项。

    request = Typhoeus::Request.new(url,
                                    method: method,
                                    params: params,
                                    body: body,
                                    headers: request_headers,
                                    cache_ttl: 10, 
                                    cache_key: "unique_key")
    
    request.run
    

    ttl 以秒为单位。 Typhoeus cache_key 默认为:

    Digest::SHA1.hexdigest "#{self.class.name}#{base_url}#{hashable_string_for(options)}"
    

    他们没有记录。您必须查看来源才能弄清楚。
    可能没问题,但我会在上面演示如何设置您自己的。

    如果您想在不使用缓存传递缓存的情况下发出请求:选项中的 false,因为缓存将默认为所有请求启用。

    【讨论】:

      【解决方案2】:

      只是为了回应https://stackoverflow.com/users/215708/jacklin 所说的话 对我有用的最简单的选择是:

      1. 如前所述,使用所需的缓存中间件配置 rails cache
      2. 在配置文件config/initializers/typhoeus.rb 中点 Typhoeus 以使用 rails 缓存,如下所示
      require 'typhoeus/cache/rails'
      Typhoeus::Config.cache = Typhoeus::Cache::Rails.new
      
      1. 就是这样。Typhoeus::Request.new 调用将被自动缓存。

      使用 Redis 的注意事项 response.body 对象是我在使用 Rails 缓存后发现的字符串类型。由于您想缓存响应并继续引用缓存 JSON.parse(response.body) 应该给您一个哈希值。我相信它是一个 redis 的东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-07
        • 2018-11-09
        • 1970-01-01
        • 2016-06-01
        • 2015-01-24
        • 2021-01-15
        • 2016-12-16
        • 2021-10-13
        相关资源
        最近更新 更多