【问题标题】:Threading HTTP requests in Crystal在 Crystal 中处理 HTTP 请求
【发布时间】:2018-03-05 14:14:13
【问题描述】:

我的代码需要“并行”运行(不是真的,我知道 Crystal 不支持并行)。

require "http/client"

thread_count = 4
resps = [] of HTTP::Client::Response
mutex = Thread::Mutex.new

urls = [] of String
(1..10).each { |i| urls << "http://httpbin.org/delay#{i}"}

threads = Array.new(thread_count) {
  Thread.new do
    while url = mutex.synchronize { urls.pop? }
      resp = HTTP::Client.get(url)
      mutex.synchronize { resps << resp }
    end
  end
}

threads.map(&.join)

Thread 类的源文件说不要使用它。无论如何,这段代码不适用于HTTP::Client

【问题讨论】:

标签: crystal-lang


【解决方案1】:

使用spawn:

require "http/client"
require "json"

WORKER_COUNT = 4

to_fetch = Channel(String?).new(WORKER_COUNT)
responses = Channel(HTTP::Client::Response?).new(WORKER_COUNT)

WORKER_COUNT.times do
  spawn do
    loop do
      url = to_fetch.receive
      responses.send url ? HTTP::Client.get(url) : nil
      break unless url
    end
  end
end

spawn do
  10.times do |i|
    to_fetch.send "http://httpbin.org/delay/#{i}"
  end
  WORKER_COUNT.times do
    to_fetch.send nil
  end
end

start = Time.local
worker_done_count = 0
loop do
  response = responses.receive
  if response
    puts "#{Time.local - start}: fetched #{JSON.parse(response.body)["url"]}"
  else
    worker_done_count += 1
    break if worker_done_count == WORKER_COUNT
  end
end

【讨论】:

  • 非常感谢!这正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 2010-12-08
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 2012-12-12
  • 2015-09-19
  • 1970-01-01
相关资源
最近更新 更多