From a49cb2848015b55f1cdfae55c0ec0cce077665b5 Mon Sep 17 00:00:00 2001 From: Dylan Carney Date: Thu, 5 Feb 2015 13:25:01 -0800 Subject: [PATCH] producer: Adds a Ping method in order to validate an nsqd connection Signed-off-by: dcarney --- producer.go | 17 +++++++++++++++++ producer_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/producer.go b/producer.go index 964c16d9..1018d26a 100644 --- a/producer.go +++ b/producer.go @@ -91,6 +91,23 @@ func NewProducer(addr string, config *Config) (*Producer, error) { return p, nil } +// Ping causes the Producer to connect to it's configured nsqd (if not already +// connected) and send a `Nop` command, returning any error that might occur. +// +// This method can be used to verify that a newly-created Producer instance is +// configured correctly, rather than relying on the lazy "connect on Publish" +// behavior of a Producer. +func (w *Producer) Ping() error { + if atomic.LoadInt32(&w.state) != StateConnected { + err := w.connect() + if err != nil { + return err + } + } + + return w.conn.WriteCommand(Nop()) +} + // SetLogger assigns the logger to use as well as a level // // The logger parameter is an interface that requires the following diff --git a/producer_test.go b/producer_test.go index 1371aa2e..04f3db05 100644 --- a/producer_test.go +++ b/producer_test.go @@ -3,6 +3,9 @@ package nsq import ( "bytes" "errors" + "io/ioutil" + "log" + "os" "runtime" "strconv" "sync" @@ -53,6 +56,28 @@ func TestProducerConnection(t *testing.T) { } } +func TestProducerPing(t *testing.T) { + log.SetOutput(ioutil.Discard) + defer log.SetOutput(os.Stdout) + + config := NewConfig() + w, _ := NewProducer("127.0.0.1:4150", config) + w.SetLogger(nullLogger, LogLevelInfo) + + err := w.Ping() + + if err != nil { + t.Fatalf("should connect on ping") + } + + w.Stop() + + err = w.Ping() + if err != ErrStopped { + t.Fatalf("should not be able to ping after Stop()") + } +} + func TestProducerPublish(t *testing.T) { topicName := "publish" + strconv.Itoa(int(time.Now().Unix())) msgCount := 10