標籤:
一 環境依賴:
golang 開發環境(version >= 1.2) 下源碼,配置環境變數,執行安裝指令碼
gpm 依賴包管理器 ubantu: sudo apt-get intall gpm
二 NSQ安裝:
- git擷取源碼: mkdir -p $GOPATH/src/github.com/nsqio;cd $GOPATH/src/github.com/nsqio;git clone https://github.com/nsqio/nsq.git;cd nsq
- 安裝依賴包: gpm install
- 安裝NSQ: go install ./...
三 開啟NSQ:
- nsqd節點維護進程:nsqlookupd &
- nsqd節點進程:nsqd --lookupd-tcp-address=127.0.0.1:4160 &
- 訊息產看進程:nsqadmin --lookupd-http-address=127.0.0.1:4161 &
ps:nsqlookupd與nsqadmin為輔助進程,可不使用直接用nsqd也可正常工作.
這裡開啟的進程均用預設的連接埠
四 工具測試:
- curl -d ‘hello world 1‘ ‘http://127.0.0.1:4151/put?topic=test‘ // 產生一個topic為“test” 訊息內容為“hello world”的訊息
- nsq_to_file --topic=test --output-dir=./tmp --lookupd-http-address=127.0.0.1:4161 // 將topic為“test”的訊息寫到./tmp目錄下的一個檔案中
五 代碼測試:
1 package main 2 3 import ( 4 "fmt" 5 "time" 6 7 "github.com/nsqio/go-nsq" 8 ) 9 10 // nsq發布訊息11 func Producer() {12 p, err := nsq.NewProducer("127.0.0.1:4150", nsq.NewConfig()) // 建立生產者13 if err != nil {14 panic(err)15 } 16 17 if err := p.Publish("test", []byte("hello NSQ!!!")); err != nil { // 發布訊息18 panic(err)19 } 20 }21 22 // nsq訂閱訊息23 type ConsumerT struct{}24 25 func (*ConsumerT) HandleMessage(msg *nsq.Message) error {26 fmt.Println(string(msg.Body))27 return nil 28 }29 30 func Consumer() {31 c, err := nsq.NewConsumer("test", "test-channel", nsq.NewConfig()) // 建立一個消費者32 if err != nil {33 panic(err)34 } 35 c.AddHandler(&ConsumerT{}) // 添加訊息處理36 if err := c.ConnectToNSQD("127.0.0.1:4150"); err != nil { // 建立串連37 panic(err)38 } 39 }40 // 主函數41 func main() {42 Producer()43 Consumer()44 time.Sleep(time.Second * 3)45 }46 // 運行將會列印: hello NSQ!!! 六 使用總結:
單機使用條件,同步發布訊息速度也非常快(10w/s),發布訊息端基本無需再做緩衝封裝。接收端的訊息處理應耗時盡量的短,避免訊息積累,當訊息積累到NSQ的緩衝的數量會將多餘的訊息寫到檔案,此時也會減緩發送端的發送速度,
因此,對接收端可使用channel和go routine做簡單封裝處理。若某topic訊息產生太快太多也可將其單獨使用一個nsqd處理,避免訊息積累影響其它訊息投遞與接收。
NSQ官方使用介紹
NSQ源碼地址
NSQ用戶端代碼地址
go-nsq使用簡述