ruby - 具有 em-synchrony 的 EventMachine 我需要正确地限制我的 http 请求

标签 ruby http asynchronous eventmachine fibers

我有一个消费者通过事件订阅从队列中提取消息。它接收这些消息,然后连接到一个相当慢的 http 接口(interface)。我有一个 8 人的工作池,一旦这些都填满,我就需要停止从队列中提取请求,并让处理 http 作业的纤程继续工作。这是我拼凑的一个例子。

def send_request(callback)
  EM.synchrony do

    while $available <= 0

      sleep 2 

      puts "sleeping"
    end 
    url = 'http://example.com/api/Restaurant/11111/images/?image%5Bremote_url%5D=https%3A%2F%2Firs2.4sqi.net%2Fimg%2Fgeneral%2Foriginal%2F8NMM4yhwsLfxF-wgW0GA8IJRJO8pY4qbmCXuOPEsUTU.jpg&image%5Bsource_type_enum%5D=3'
    result = EM::Synchrony.sync EventMachine::HttpRequest.new(url, :inactivity_timeout => 0).send("apost", :head => {:Accept => 'services.v1'})

    callback.call(result.response) 
  end 
end

def display(value)
  $available += 1
  puts value.inspect
end

$available = 8 

EM.run do
  EM.add_periodic_timer(0.001) do
    $available -= 1
    puts "Available: #{$available}"

    puts "Tick ..." 
    puts send_request(method(:display))
  end 

end

我发现如果我在同步块(synchronized block)的 while 循环中调用 sleep, react 器循环就会卡住。如果我在 if 语句中调用 sleep(只睡一次),那么大多数时候请求完成的时间已经足够了,但它充其量是不可靠的。如果我使用 EM::Synchrony.sleep,那么主 react 器循环将继续创建新请求。

有没有办法暂停主循环但让纤程完成它们的执行?

最佳答案

sleep 2

...

add_periodic_timer(0.001)

你是认真的吗?

您有没有想过有多少 send_request 在循环中休眠?它每秒增加 1000。

这个怎么样:

require 'eventmachine'
require 'em-http'
require 'fiber'

class Worker
  URL = 'http://example.com/api/whatever'

  def initialize callback
    @callback = callback
  end

  def work
    f = Fiber.current
    loop do
      http = EventMachine::HttpRequest.new(URL).get :timeout => 20

      http.callback do
        @callback.call http.response
        f.resume
      end
      http.errback do
        f.resume
      end

      Fiber.yield
    end
  end
end

def display(value)
  puts "Done: #{value.size}"
end

EventMachine.run do
  8.times do
    Fiber.new do
      Worker.new(method(:display)).work
    end.resume
  end
end

关于ruby - 具有 em-synchrony 的 EventMachine 我需要正确地限制我的 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12264036/

相关文章:

ruby-on-rails - Ruby on Rails 数组迭代

ruby - 如何使用 ruby​​wmq gem 将消息发布到 IBM WebsphereMQ TOPIC

c++ - 使用 http post 在 FCM 中推送通知

c# - 异步/等待与线程场景

multithreading - for循环中的异步请求返回

php - 使用 WEBrick 为 PHP Web 应用程序提供服务

ruby-on-rails - 在第三页上没有获取下一页 token google place api?

node.js - 将 .htacees 指向使用 SSL 配置的 Node 服务器

http - 转义http请求中的感叹号

ios - 如何创建异步 NSOperation iOS?