研究完了消费者,那么我们就要看看生产者是如何工作的
// Producer 生产者
func Producer() {
producer, err := nsq.NewProducer("127.0.0.1:4150", nsq.NewConfig())
if err != nil {
fmt.Println("NewProducer", err)
panic(err)
}
i := 1
for {
if err := producer.Publish("test", []byte(fmt.Sprintf("Hello World %d", i))); err != nil {
fmt.Println("Publish", err)
panic(err)
}
time.Sleep(time.Second * 5)
i++
}
}
首先通过nsq的NewProducer的方法构建了一个producer,注意在这里传入的adder是nsqd的地址,接下来就是调用producer的publish将我们要发送的topic和消息发布出去
func (w *Producer) Publish(topic string, body []byte) error {
return w.sendCommand(Publish(topic, body))
}
调用Publish方法,将topic和要发布的消息封装程command:
func Publish(topic string, body []byte) *Command {
var params = [][]byte{[]byte(topic)}
return &Command{[]byte("PUB"), params, body}
}