NATSGo是NATS的Go客户端。
安装:
# Go clientgo get github.com/nats-io/nats# Servers# gnatsdgo get github.com/nats-io/gnatsd# nats-server (Ruby)gem install nats基础编码使用
nc, _ := nats.Connect(nats.DefaultURL)c, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER)defer c.Close()// Simple Publisherc.Publish("foo", "Hello World")// Simple Async Subscriberc.Subscribe("foo", func(s string) { fmt.Printf("Received a message: %s\n", s)})// EncodedConn can Publish any raw Go type using the registered Encodertype person struct { Name string Address string Age int}// Go type Subscriberc.Subscribe("hello", func(p *person) { fmt.Printf("Received a person: %+v\n", p)})me := &person{Name: "derek", Age: 22, Address: "585 Howard Street, San Francisco, CA"}// Go type Publisherc.Publish("hello", me)// Unsubscribingsub, err := c.Subscribe("foo", nil)...sub.Unsubscribe()// Requestsvar response stringerr := nc.Request("help", "help me", &response, 10*time.Millisecond)// Replyingc.Subscribe("help", func(subj, reply string, msg string) { c.Publish(reply, "I can help!")})// Close connectionc.Close();
评论