如何在Rails中缓存带有Typhoeus gem的api请求?在尝试了2次horus之后,我放弃了自己尝试。
我有以下代码:
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但是我不知道把这段代码放在哪里。
发布于 2021-05-02 21:46:29
创建一个初始化器来设置缓存。类似于:(config/initializers/tytyeus.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.runttl以秒为单位。默认情况下,台风cache_key为:
Digest::SHA1.hexdigest "#{self.class.name}#{base_url}#{hashable_string_for(options)}"他们没有记录这一点。你必须看看它的来源才能找出答案。
这可能是好的,但我演示了如何设置您自己的,如果您想要上面。
如果你想在不使用缓存的情况下发出请求,在选项中传递cache: false,因为缓存现在对所有请求都是默认开启的。
发布于 2021-11-28 06:26:46
就像https://stackoverflow.com/users/215708/jacklin说的,对我来说最简单的选择是:
如前所述,在配置文件config/initializers/typhoeus.rb中使用所需的缓存middleware
rails cache以使用rails缓存,如下所示require 'typhoeus/cache/rails'
Typhoeus::Config.cache = Typhoeus::Cache::Rails.newTyphoeus::Request.new调用将被自动缓存。旁注:如果使用Redis,response.body对象的类型是string,这是我在使用Rails缓存后发现的。因为您希望缓存响应并不断引用缓存,所以JSON.parse(response.body)应该给您一个哈希值。我相信这是红色的东西。
https://stackoverflow.com/questions/67329880
复制相似问题