gpt4 book ai didi

ruby - Http.rb 和 Celluloid 超时的解决方法?

转载 作者:可可西里 更新时间:2023-11-01 16:55:59 25 4
gpt4 key购买 nike

我知道 Http.rb 和 Celluloid[1] 目前不支持当前超时,但是否有临时解决方法?

这是我要运行的代码:

  def fetch(url, options = {} )
puts "Request -> #{url}"
begin
options = options.merge({ socket_class: Celluloid::IO::TCPSocket,
timeout_class: HTTP::Timeout::Global,
timeout_options: {
connect_timeout: 1,
read_timeout: 1,
write_timeout: 1
}
})
HTTP.get(url, options)
rescue HTTP::TimeoutError => e
[do more stuff]
end
end

它的目标是测试服务器是否正常运行。我愿意接受替代方案(例如 %x(ping <server>) ),但这些方案似乎效率较低,但实际上能够得到我正在寻找的东西。

[1] https://github.com/httprb/http.rb#celluloidio-support

最佳答案

您可以在获取请求时为以后的调用设置超时

这里是如何在 Http.rb 和 Celluloid-io 中使用超时

require 'celluloid/io'
require 'http'
TIMEOUT = 10 # in sec
class HttpFetcher
include Celluloid::IO

def fetch(url)
HTTP.get(url, socket_class: Celluloid::IO::TCPSocket)
rescue Exception => e
# error
end
end

fetcher = HttpFetcher.new

urls = %w(http://www.ruby-lang.org/ http://www.rubygems.org/ http://celluloid.io/)

# Kick off a bunch of future calls to HttpFetcher to grab the URLs in parallel
futures = urls.map { |u| [u, fetcher.future.fetch(u)] }

# Consume the results as they come in
futures.each do |url, future|
# Wait for HttpFetcher#fetch to complete for this request
response = future.value(TIMEOUT)
puts "*** Got #{url}: #{response.inspect}\n\n"
end

关于ruby - Http.rb 和 Celluloid 超时的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30196545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com