使用 Ruby Net 实施重新连接策略
我正在开发一个小型应用程序,它将 XML 发布到某些 Web 服务。 这是使用 Net::HTTP::Post::Post 完成的。 但是,服务提供商建议使用重新连接。
就像是: 第一个请求失败 -> 2秒后重试 第二次请求失败 -> 5秒后重试 第三次请求失败 -> 10秒后重试 ...
这样做的好方法是什么? 简单地在循环中运行以下代码,捕获异常并在一段时间后再次运行它? 或者还有其他聪明的方法可以做到这一点吗? 也许 Net 包甚至有一些我不知道的内置功能?
url = URI.parse("http://some.host")
request = Net::HTTP::Post.new(url.path)
request.body = xml
request.content_type = "text/xml"
#run this line in a loop??
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
非常感谢,始终感谢您的支持。
马特
I'm developing a small application which posts XML to some webservice.
This is done using Net::HTTP::Post::Post. However, the service provider recommends using a re-connect.
Something like:
1st request fails -> try again after 2 seconds
2nd request fails -> try again after 5 seconds
3rd request fails -> try again after 10 seconds
...
What would be a good approach to do that? Simply running the following piece of code in a loop, catching the exception and run it again after an amount of time? Or is there any other clever way to do that? Maybe the Net package even has some built in functionality that I'm not aware of?
url = URI.parse("http://some.host")
request = Net::HTTP::Post.new(url.path)
request.body = xml
request.content_type = "text/xml"
#run this line in a loop??
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
Thanks very much, always appreciate your support.
Matt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 Ruby 的
retry
派上用场的罕见情况之一。 沿着这些思路:This is one of the rare occasions when Ruby's
retry
comes in handy. Something along these lines:我使用 gem retryable 进行重试。
有了它,代码从:
到:
I use gem retryable for retry.
With it code transformed from:
To: