Skip to content

Commit

Permalink
producer: Adds a Ping method in order to validate an nsqd connection
Browse files Browse the repository at this point in the history
Signed-off-by: dcarney <dcarney@gmail.com>
  • Loading branch information
dcarney committed Feb 23, 2015
1 parent a03f590 commit a49cb28
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
17 changes: 17 additions & 0 deletions producer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions producer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package nsq
import (
"bytes"
"errors"
"io/ioutil"
"log"
"os"
"runtime"
"strconv"
"sync"
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit a49cb28

Please sign in to comment.