Rails:使用Typhoeus缓存API请求



如何在Rails中使用Typhoeus-gem缓存api请求?经过两个小时的尝试,我放弃了自己做这件事。

我有以下代码:

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

但我不明白该把这个代码放在哪里。

创建一个初始值设定项来设置缓存。类似于:(config/ininitializers/typoeus.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以秒为单位。伤寒cache_key默认为:

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

他们没有记录。你必须查看来源才能弄清楚
这可能很好,但如果您愿意,我将演示如何设置您自己的。

如果您想在不使用缓存传递缓存的情况下发出请求,请在选项中选择false,因为默认情况下,所有请求的缓存现在都会打开。

只是为了呼应什么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)应该给您一个散列。我相信这是一件大事。

最新更新