Browse files

Resolve non-IP hosts to an IP immediately rather than incur a DNS loo…

…kup for each socket send

Addresses issue #5 - thanks @mdp!
  • Loading branch information...
1 parent 86a4bfe commit 8bcb43dfb3e449935b9a219a8c49896caa8ead9e @jeremy committed Dec 3, 2011
Showing with 25 additions and 6 deletions.
  1. +14 −2 lib/statsd.rb
  2. +11 −4 spec/statsd_spec.rb
View
16 lib/statsd.rb
@@ -17,7 +17,8 @@ class Statsd
attr_reader :namespace
# StatsD host. Defaults to 127.0.0.1.
- attr_accessor :host
+ # Setting a hostname resolves to an IP address to avoid excess DNS lookups.
+ attr_reader :host
# StatsD port. Defaults to 8125.
attr_accessor :port
@@ -37,7 +38,7 @@ def logger=(logger) #:nodoc:
# @param [String] host your statsd host
# @param [Integer] port your statsd port
def initialize(host='127.0.0.1', port=8125)
- @host, @port = host, port
+ self.host, self.port = host, port
@prefix = nil
@socket = UDPSocket.new
end
@@ -47,6 +48,17 @@ def namespace=(namespace) #:nodoc:
@prefix = "#{namespace}."
end
+ # If the argument is a hostname, resolve it to an IP address.
+ def host=(host) #:nodoc:
+ require 'ipaddr'
+ begin
+ @host = IPAddr.new(host).to_s
+ rescue ArgumentError
+ require 'resolv'
+ @host = Resolv.getaddress(host)
+ end
+ end
+
# Sends an increment (count = 1) for the given stat to the statsd server.
#
# @param [String] stat stat name
View
15 spec/statsd_spec.rb
@@ -7,15 +7,15 @@ class Statsd
end
before do
- @statsd = Statsd.new('localhost', 1234)
+ @statsd = Statsd.new('1.2.3.4', 1234)
@statsd.socket = FakeUDPSocket.new
end
after { @statsd.socket.clear }
describe "#initialize" do
it "should set the host and port" do
- @statsd.host.must_equal 'localhost'
+ @statsd.host.must_equal '1.2.3.4'
@statsd.port.must_equal 1234
end
@@ -27,12 +27,19 @@ class Statsd
end
describe "#host and #port" do
+ before { require 'resolv'; def Resolv.getaddress(host) '127.0.0.1' end }
+
it "should set host and port" do
- @statsd.host = '1.2.3.4'
+ @statsd.host = '5.6.7.8'
@statsd.port = 5678
- @statsd.host.must_equal '1.2.3.4'
+ @statsd.host.must_equal '5.6.7.8'
@statsd.port.must_equal 5678
end
+
+ it "should resolve hostnames to IPs" do
+ @statsd.host = 'localhost'
+ @statsd.host.must_equal '127.0.0.1'
+ end
end
describe "#increment" do

0 comments on commit 8bcb43d

Please sign in to comment.