NATS Go 是 [NATS](http://www.oschina.net/p/nats) 的 Go 客户端。
安装:
<pre class="brush:shell;toolbar: true; auto-links: false;"># Go client
go get github.com/nats-io/nats
# Servers
# gnatsd
go get github.com/nats-io/gnatsd
# nats-server (Ruby)
gem install nats</pre>
基础编码使用
<pre class="brush:shell;toolbar: true; auto-links: false;">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();</pre>