PUBLISHER 代码:
func main() {
nc,err := stan.Connect("test-cluster","idc",stan.NatsURL("nats://127.0.0.1:4222"))
if err != nil{
panic(err)
}
fmt.Println("connect succ")
for i:=0;i<10;i++{
fmt.Println("publishing:",i)
err := nc.Publish("tp1",[]byte(strconv.Itoa(i)))
if err != nil{
panic(err)
}
}
nc.Close()
}
QueueSubscriber 代码:
func main() {
nc,err := stan.Connect("test-cluster","subscriber",stan.NatsURL("nats://localhost:4222"))
if err != nil{
panic(err)
}
defer nc.Close()
subs := make([]stan.Subscription,3)
for i:=0;i<3;i++{
workername := "worker"+strconv.Itoa(i)
fmt.Println(fmt.Sprintf("QueueSubscribe %s start",workername))
sub,err := nc.QueueSubscribe("tp1","ch1", func(msg *stan.Msg) {
fmt.Println(workername,"get msg:",string(msg.Data),"start doing something")
time.Sleep(1*time.Second)
},stan.DurableName("subscriber"),stan.AckWait(time.Hour*24))
if err != nil{
panic(err)
}
subs[i] = sub
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
select{
case <- c:
fmt.Println("Subscriber CLOSE")
for i,_ := range subs{
subs[i].Close()
}
nc.Close()
fmt.Println("quit")
}
}
Publisher 输出:
connect succ
publishing: 0
publishing: 1
publishing: 2
publishing: 3
publishing: 4
publishing: 5
publishing: 6
publishing: 7
publishing: 8
publishing: 9
QueueSubscriber 输出:
QueueSubscribe worker0 start
QueueSubscribe worker1 start
worker0 get msg: 0 start doing something
QueueSubscribe worker2 start
worker0 get msg: 1 start doing something
worker0 get msg: 2 start doing something
worker0 get msg: 3 start doing something
worker0 get msg: 4 start doing something
worker0 get msg: 5 start doing something
worker0 get msg: 6 start doing something
worker0 get msg: 7 start doing something
worker0 get msg: 8 start doing something
worker0 get msg: 9 start doing something
请问朋友们是否有遇到过一样的问题呢?谢谢大家
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.