介绍
NSQ是一个实时的分布式消息传递平台,主要成分:nsqlookupd、nsqd、nsqadmin。
安装(docker)
- 拉取镜像 :
docker pull nsqio/nsq
- nsqlookupd: 管理拓扑信息并提供最终一致的发现服务的守护程序。
docker run --name lookupd -p 4160:4160 -p 4161:4161 -d nsqio/nsq /nsqlookupd
- nsqd: 接收、排队并将消息传递到客户端的核心守护线程;(127.0.0.1 要是云服务的话就替换成外网地址)
docker run --name nsqd -p 4150:4150 -p 4151:4151 -d nsqio/nsq /nsqd --broadcast-address=127.0.0.1 --lookupd-tcp-address=127.0.0.1:4160
- nsqadmin: 消息管理平台
docker run -d --name nsqadmin -p 4171:4171 nsqio/nsq /nsqadmin --lookupd-http-address=127.0.0.1:4161
- nsq核心概念 :topic:主题、channel:通道
使用(Go语言-代码实现)
客户端(生产者)
func main() {
cfg := nsq.NewConfig()
nsqd := "127.0.0.1:4150" // nsq地址
producer, err := nsq.NewProducer(nsqd, cfg)
if err != nil {
fmt.Println("err:", err)
}
messa := "消息内容-消息体"
aa, _ := json.Marshal(messa)
//msg_service: 主题名, aa: 消息内容json
if err := producer.Publish("msg_service", aa); err != nil {
fmt.Println("publish error:", err)
}
fmt.Println("is: ", producer.String())
}
服务端(消费者)
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.
// In this case, a message with an empty body is simply ignored/discarded.
return nil
}
fmt.Println("body: ", string(m.Body))
// do whatever actual message processing is desired
//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()
//msg_service:主题名, lpp_channel:通道
consumer, err := nsq.NewConsumer("msg_service", "lpp_channel", 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.
adds := "127.0.0.1:4150" //nsq服务地址
err = consumer.ConnectToNSQD(adds)
if err != nil {
log.Fatal(err)
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
fmt.Println("rest :", <-sigChan)
// wait for signal to exit
// Gracefully stop the consumer.
consumer.Stop()
}
效果图(nsqadmin)
emmm 到这里 就算是搭建结束了,具体的可以根据自己的因为实现。