首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Http.rb和Celluloid超时的解决方法?

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

Stack Overflow用户
提问于 2015-05-13 00:26:14
回答 1查看 394关注 0票数 1

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

下面是我想要运行的代码:

代码语言:javascript
复制
  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

EN

回答 1

Stack Overflow用户

发布于 2015-05-21 01:01:58

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

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

代码语言:javascript
复制
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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30196545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档