如何解决如何确保我使用同一会话进行多个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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。