LoginSignup
3
1

More than 5 years have passed since last update.

RubyのNet::HTTPでKeep-Aliveが有効にならない件

Last updated at Posted at 2017-06-24

TLDR

Net::HTTP.start("httpbin.org", 80) do |http|
  # 複数のリクエストを投げる
end

という形式だとKeep-Aliveが有効になる(TCPコネクションが使いまわされる)。

http = Net::HTTP.start("httpbin.org", 80)
# 複数のリクエストを投げる

という形式でも有効になる。

http = Net::HTTP.new("httpbin.org", 80)
http.start     # このstartを忘れると有効にならない
# 複数のリクエストを投げる

という形式でも有効になる。

確認用スクリプト

OK

require "net/http"

# 同じホストに対して2回リクエストを送る
Net::HTTP.start("httpbin.org", 80) do |http|
  2.times do
    req = Net::HTTP::Get.new "/get"
    req["Connection"] = "Keep-Alive"
    res = http.request req # Net::HTTPResponse object
    p res
    res.each do |k, v|
      puts "#{k}: #{v}"
    end
  end
end

NG

require "net/http"

# 1回だけNet::HTTP.newして使いまわす
http = Net::HTTP.new("httpbin.org", 80)

# 同じホストに対して2回リクエストを送る
2.times do
  req = Net::HTTP::Get.new("/get")
  req["Connection"] = "Keep-Alive"
  res = http.request(req)
  p res
  res.each do |k, v|
    puts "#{k}: #{v}"
  end
end

NGの方だと、サーバはちゃんとconnection: keep-aliveを返してきているにも関わらず、リクエストの度にコネクションが張られてしまう。そのことはtcpdump -nn port 80で見るとSYN, FINが送られていることで確認できるし、Rubyが使うエフェメラルポートも変わっている。

3
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1