GitHub https://github.com/nsqio/nsq
1、注意:需要提前安装go
设置好GOROOT、GOPATH、GOBIN
2、安装NSQ
git clone https://github.com/nsqio/nsq.git $GOPATH/src/github.com/nsqio/nsq
#install nsqd
git clone https://github.com/blang/semver.git $GOPATH/src/github.com/blang/semver
git clone https://github.com/bmizerany/perks.git $GOPATH/src/github.com/bmizerany/perks
git clone https://github.com/golang/snappy.git $GOPATH/src/github.com/golang/snappy
git clone https://github.com/nsqio/go-diskqueue.git $GOPATH/src/github.com/nsqio/go-diskqueue
git clone https://github.com/nsqio/go-nsq.git $GOPATH/src/github.com/nsqio/go-nsq
go build -o $GOBIN/nsqd $GOPATH/src/github.com/nsqio/nsq/apps/nsqd/*.go
#install nsqlookupd, nsqlookupd is not necessary
git clone https://github.com/BurntSushi/toml.git $GOPATH/src/github.com/BurntSushi/toml
git clone https://github.com/judwhite/go-svc.git $GOPATH/src/github.com/judwhite/go-svc
git clone https://github.com/julienschmidt/httprouter.git $GOPATH/src/github.com/julienschmidt/httprouter
git clone https://github.com/mreiferson/go-options.git $GOPATH/src/github.com/mreiferson/go-options
go build -o $GOBIN/nsqlookupd $GOPATH/src/github.com/nsqio/nsq/apps/nsqlookupd/*.go
3、运行
运行nsqd,(nsqlookup不是一定需要的)
nsqd #--lookupd-tcp-address=127.0.0.1:4160 #-tcp-address="0.0.0.0:4150" #defualt listen port
#nsqlookupd
producer:
package main
import (
"github.com/nsqio/go-nsq"
"fmt"
)
func main(){
prodocer,err := nsq.NewProducer("127.0.0.1:4150",nsq.NewConfig())
if err != nil{
fmt.Println(err)
return
}
for i:= 0;i<1000;i++{
if err := prodocer.Publish("test2",[]byte(fmt.Sprintf("hello world %d",i)));err != nil{
fmt.Println(err)
break
}
}
prodocer.Stop()
}
consumer:
package main
import (
"github.com/nsqio/go-nsq"
"fmt"
)
var count int
type handler struct{
c chan bool
}
func (this *handler)HandleMessage(message *nsq.Message) error{
fmt.Println("receve:",message.ID,string(message.Body))
if count++;count >= 1000{
close(this.c)
}
return nil
}
func main(){
count = 0
config := nsq.NewConfig()
consumer,err := nsq.NewConsumer("test2","test-channel",config)
if err != nil{
fmt.Println(err)
return
}
H := handler{c:make(chan bool)}
consumer.AddHandler(&H)
//if err = consumer.ConnectToNSQLookupd("127.0.0.1:4161");err != nil{
if err = consumer.ConnectToNSQ("127.0.0.1:4150");err != nil{
fmt.Println(err)
consumer.Stop()
}
var j bool
for i := range H.c{
j = i
}
fmt.Println(j)
consumer.Stop()
}
consumer可以监听同一topic,不同的channel,能够同时接收相同的消息。
参考:
https://nsq.io/overview/quick_start.html
https://blog.youkuaiyun.com/qq_26981997/article/details/56673522
https://www.jianshu.com/p/b19f962a99c7
https://segmentfault.com/a/1190000009194607
https://blog.youkuaiyun.com/jeffrey11223/article/details/80613500