如何确保我使用同一会话进行多个HTTP调用?

问题描述

比方说,我从一个循环内部调用以下代码,每次迭代与URL之间有1秒的睡眠/延迟是一个API。如何确保Net :: HTTP对所有调用都使用相同的API会话?我知道文档说Net :: HTTP.new将尝试重用相同的连接。但是我该如何验证呢?是否可以从Net :: HTTP中提取会话ID?

request = Net::HTTP::Put.new(url)

url = URI(url)

http = Net::HTTP.new(url.host,url.port)
http.use_ssl = true

request["Accept"] = 'application/json'
request["Content-Type"] = 'application/json'
request["Authorization"] = @auth_key
request["cache-control"] = 'no-cache'

request.body = request_body.to_json if request_body
response = http.request(request)

解决方法

针对您所运行的红宝石版本仔细检查以下内容

对于一个,我认为我看不到任何会话ID ,这将是非常有用的功能。接下来,查看源代码,我们在lib/net/http.rb中以如下方法查看变量设置:

def do_finish
  @started = false
  @socket.close if @socket
  @socket = nil
end

# Returns true if the HTTP session has been started.
def started?
  @started
end

# Finishes the HTTP session and closes the TCP connection.
# Raises IOError if the session has not been started.
def finish
  raise IOError,'HTTP session not yet started' unless started?
  do_finish
end

do_finish将实例变量@socket设置为nil,而@socket用作BufferedIO实例以通过HTTP运行HTTP请求

因此,我将为finish方法编写一个重写方法,并在调用do_finish时发出警报。

浏览注释start是使用同一会话的最安全选择,因此您可以使用起始块并比较实例变量的ID不变

Net::HTTP.start(url) do |http|
  before = http.instance_variable_get(:@socket)
  loop do
    instance_var = http.instance_variable_get(:@socket)
    break unless before == instance_var
  end
end