topic的作用
topic的作用就和收发快递选哪个快递一样,你选择顺丰,选择圆通。收快件(消费消息)的时候都用这个topic,应该没人收顺丰快递跑到圆通的网点吧。
channel的作用
- 消息复制
channel是有大作用的,主要体现在消息复制上。你想实现一条消息两个业务都收到。这里做法就需要用到channel,在同一样topic下面创建两个channel,ch1和ch2。生产者发一条hello nsq,这时候两个业务都会收到hello nsq。(下面给代码验证这个结论) - 默认用法
如不需消息复制,就一个topic,一个channel就完事。
生产者
这里的topic是test,下面的ip是nsqd的地址。
curl -d 'hello ch16' 'http://192.168.6.100:4251/pub?topic=test'
消费者
可以把下面的代码复制两份,channel修改为ch1和ch2。
package main
import (
"fmt"
"github.com/nsqio/go-nsq"
"log"
"time"
)
type myMessageHandler struct{}
// HandleMessage implements the Handler interface.
func (h *myMessageHandler) HandleMessage(m *nsq.Message) error {
if len(m.Body) == 0 {
// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.
fmt.Printf("body is empty\n")
return nil
}
fmt.Printf("------------>:%s\n", m.Body)
//err := processMessage(m.Body)
// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.
return nil
}
func main() {
// Instantiate a consumer that will subscribe to the provided channel.
config := nsq.NewConfig()
config.MaxInFlight = 2
consumer, err := nsq.NewConsumer("test", "ch2", config)
if err != nil {
log.Fatal(err)
}
// Set the Handler for messages received by this Consumer. Can be called multiple times.
// See also AddConcurrentHandlers.
consumer.AddHandler(&myMessageHandler{})
// Use nsqlookupd to discover nsqd instances.
// See also ConnectToNSQD, ConnectToNSQDs, ConnectToNSQLookupds.
err = consumer.ConnectToNSQLookupd("192.168.6.100:4161")
if err != nil {
log.Fatal(err)
}
// Gracefully stop the consumer.
for {
time.Sleep(time.Second)
}
consumer.Stop()
}
网友评论