nsq中topic和channel的作用

2020-04-02  本文已影响0人  guonaihong

topic的作用

topic的作用就和收发快递选哪个快递一样,你选择顺丰,选择圆通。收快件(消费消息)的时候都用这个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()
}

上一篇 下一篇

猜你喜欢

热点阅读