2

我有一个非常通用的连接脚本来连接 nats 服务器,只是盲目地将消息打印到命令行。

package main
import (
    "github.com/nats-io/go-nats"
    "fmt"
)


func main(){

    servers := "nats://URL:30401, nats://URL:30402, nats://URL:30403"
    nc, _ := nats.Connect(servers, nats.Token("TOKEN_KEY"))

    // Subscribe to AAPL trades
    nc.Subscribe("T.AAPL", func(m *nats.Msg){
        fmt.Printf("[TRADE] Received: %s\n", string(m.Data))
    })

}

它构建良好并且没有错误地运行,但实际上不会订阅。将fmt.Printf消息打印到终端的正确方法是什么?还是这里有更大的问题?

4

2 回答 2

3

Subscribe create an asynchronous listener for events on that channel. As your main function exits straight after the call to subscribe there program will edit before the asynchronous process has finished. There is also synchronised subscribe function:

https://godoc.org/github.com/nats-io/go-nats#Conn.SubscribeSync

Or you can add a wait into your main method so that it doesn't exit straight away.

于 2018-05-09T18:49:31.137 回答
0

假设您连接正常(最好在连接时捕获错误并检查它)您正在退出程序,因为它不会等待退出 main,因为订阅在他们自己的 Go 例程中创建异步订阅者。使用 runtime.Goexit() 让程序等待。类似于这个例子

于 2018-09-30T20:49:50.263 回答