ruby net/http opening connection very slow

2020-03-24 04:47发布

问题:

When I'm working with net/http in development it is extremely slow. I've installed net-http-spy gem to get some info about each request and I've found out that "opening connection" part takes the most time (more than 10 seconds). Further more, it doesn't keep connections alive, so it needs to reopen it on every request.

opening connection to maps.google.com...
# ~10 seconds
opened

Is there any way I could somehow improve the performance of net/http library by settings some of its defaults? I don't want a request specific fix, but something that would fix the issue globally. I'm using geokit gem in curent project and I cannot change the way it handles request internally, other than knowing it is using net/http, and it is working great on production (Heroku) but extremely slow in development.

I'm using ruby 1.9.2-p290 on Mac OS X Lion. Ruby is installed and managed with rbenv.


Here is the sample code:

require 'net/http'
require 'uri'

time = Time.now.to_i
uri = URI.parse("http://maps.google.com/maps/geo?q=Chicago&output=xml&oe=utf-8")

Net::HTTP.get(uri)
puts (Time.now.to_i - time)

Net::HTTP.get(uri)
puts (Time.now.to_i - time)

It doesn't really matter what URL I put in there. It always take exactly 10 seconds for each request..

回答1:

Old issue, but I recently had the same problem.

It seems to be a problem with certain versions of libc which resolve DNS routes. After spending couple hours to search solution you just need to add require 'resolv-replace' at the beginning of your code.

More information: https://github.com/ruby/ruby/pull/597#issuecomment-40507119

Hope this help somebody in the future.



回答2:

It was an issue with DNS server. Switched to google public DNS (8.8.8.8, 8.8.4.4). Thanks @Ineu.



回答3:

Eventually what solve the problem for me was disabling the Antivirus. I have Norton Security



标签: ruby net-http