NATS Go云消息系统
NATS Go 是 NATS 的 Go 客户端。
安装:
# Go client go get github.com/nats-io/nats # Servers # gnatsd go 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 Publisher c.Publish("foo", "Hello World") // Simple Async Subscriber c.Subscribe("foo", func(s string) { fmt.Printf("Received a message: %s\n", s) }) // EncodedConn can Publish any raw Go type using the registered Encoder type person struct { Name string Address string Age int } // Go type Subscriber c.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 Publisher c.Publish("hello", me) // Unsubscribing sub, err := c.Subscribe("foo", nil) ... sub.Unsubscribe() // Requests var response string err := nc.Request("help", "help me", &response, 10*time.Millisecond) // Replying c.Subscribe("help", func(subj, reply string, msg string) { c.Publish(reply, "I can help!") }) // Close connection c.Close();
评论