NSQ是由知名短鏈接服務商bitly用Go語言開發的實時消息處理系統,具有高性能、高可靠、無視單點故障等優點,是一個非常不錯的新興的消息隊列解決方案。
nsg易於配置和部署,所有參考都通過命令行指定,編譯好的二進制文件,沒有其它依賴項。而且支持多種消息格式。
關於nsq的介紹看這里:http://www.oschina.net/translate/day-22-a-journey-into-nsq
官網:http://nsq.io/overview/quick_start.html
相比之前,API更好用了。
對我來說,主要是部署簡單,方便擴展。
直接上代碼。
package main import ( "github.com/bitly/go-nsq" "fmt" "time" ) type Handle struct{ msgchan chan *nsq.Message stop bool } func (h *Handle) HandleMsg(m *nsq.Message) error { if !h.stop{ h.msgchan <- m } return nil } func (h *Handle) Process(){ h.stop = false for{ select{ case m := <-h.msgchan: fmt.Println(string(m.Body)); case <-time.After(time.Second): if h.stop{ close(h.msgchan) return } } } } func (h *Handle) Stop(){ h.stop = true } func main(){ config := nsq.NewConfig() consumer, err := nsq.NewConsumer("test", "my", config) if err != nil{ panic(err) } h := new(Handle) consumer.AddHandler(nsq.HandlerFunc(h.HandleMsg)) h.msgchan = make(chan *nsq.Message, 1024) err = consumer.ConnectToNSQD("127.0.0.1:4150") if err != nil{ panic(err) } h.Process() }
另外,nsq的 topic和channel的關系:
http://word.bitly.com/post/38385370762/spray-some-nsq-on-it
Brief tangent: NSQ has the concept of topics and channels. Basically, think of a topic as a unique stream of messages (like our stream of API events above). Think of a channel as a copy of that stream of messages for a given set of consumers. Topics and channels are both independent queues, too. These properties enable NSQ to support both multicast (a topic copying each message to N channels) and distributed (a channel equally dividing its messages among N consumers) message delivery.
在代碼里面:
consumer, err := nsq.NewConsumer("test", "my", config)
channel == my
如果有多個consumer是同一個channel的時候,消息只能被其中的一個consumer吃掉。如果多個consumer采用不同的channel,那么每個consumer都可以收到producer生產的同一個消息,這樣很方便的支持了多播和分發。
=============================================================
NSQ 和 RabiitMQ的對比
一、RabbitMQ

對於一個數據從Producer到Consumer的正確傳遞,還有三個概念需要明確:exchanges, queues and bindings。
Exchanges are where producers publish their messages.
Queuesare where the messages end up and are received by consumers
Bindings are how the messages get routed from the exchange to particular queues.
還有幾個概念是上述圖中沒有標明的,那就是Connection(連接),Channel(通道,頻道)。
Connection: 就是一個TCP的連接。Producer和Consumer都是通過TCP連接到RabbitMQ Server的。以后我們可以看到,程序的起始處就是建立這個TCP連接。
Channels: 虛擬連接。它建立在上述的TCP連接中。數據流動都是在Channel中進行的。也就是說,一般情況是程序起始建立TCP連接,第二步就是建立這個Channel。
二、NSQ

NSQ組合比較自由。
可以單獨使用nsqd,Producer和Consumer自己直接連接nsqd。
也可以利用nsqlookupd來管理nsqd(根據心跳,挑選出可用的nsqd),Producer和Consumer跟nsqlookupd來交互。
======================================
RabbitMQ里面的Exchange類似nsqd,queen類似channel。
關於RabbitMQ里面的詳細介紹可參考:http://www.diggerplus.org/archives/3110
