ruby net/http opening connection very slow

2020-03-24 04:33发布

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..

标签: ruby net-http
3条回答
走好不送
2楼-- · 2020-03-24 04:53

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

查看更多
Animai°情兽
3楼-- · 2020-03-24 04:59

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.

查看更多
smile是对你的礼貌
4楼-- · 2020-03-24 05:06

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

查看更多
登录 后发表回答