2018-05-09 18:16
浏览 103


I have a very generic connection scrip to connect a nats server and just blindly print the message to the command line.

package main
import (

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
", string(m.Data))


it builds fine and runs with out error, but wont actually subscribe. is the fmt.Printf the proper way to have the message print to terminal? or is there a bigger issue at hand here?

图片转代码服务由CSDN问答提供 功能建议

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

” fmt“ 
func main()  {
服务器:=“ nats:// URL:30401,nats:// URL:30402,nats:// URL:30403” 
 nc,_:= nats.Connect(服务器,nats.Token(  “ TOKEN_KEY”))
 nc.Subscribe(“ T.AAPL”,func(m * nats.Msg){
 fmt.Printf(“ [TRADE]收到:%s  

它可以正常运行且没有错误,但实际上不会订阅 。 fmt.Printf 是将消息打印到终端的正确方法吗? 还是这里有更大的问题?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongshou2017 2018-05-09 18:49

    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:

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

    点赞 打赏 评论
  • dpqvwgr74759 2018-09-30 20:49

    Assuming you are connecting ok (best to capture error on connect and check it) you are exiting the program since it does not wait to exit main since Subscribe creates async subscribers in their own Go routines. Use runtime.Goexit() to have the program wait. Similar to this example.

    点赞 打赏 评论

相关推荐 更多相似问题