增加 NATS Golang Client 示例代码.

Signed-off-by: rick.chan <chenyang@autoai.com>
This commit is contained in:
rick.chan 2021-06-29 16:04:33 +08:00
parent f498e91191
commit 0ad141d99e
4 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package main
import (
"fmt"
"time"
"github.com/nats-io/nats.go"
)
func main() {
nc, err := nats.Connect(nats.DefaultURL)
defer nc.Close()
if nil != err {
fmt.Println(err)
return
}
for {
nc.Publish("foo", []byte("Hello Publish!"))
time.Sleep(1 * time.Second)
}
}

View File

@ -0,0 +1,27 @@
package main
import (
"fmt"
"time"
"github.com/nats-io/nats.go"
)
func main() {
nc, err := nats.Connect(nats.DefaultURL)
defer nc.Close()
if nil != err {
fmt.Println(err)
return
}
for {
m, err := nc.Request("foo", []byte("Hello Request!"), 1*time.Second)
if nil != err {
fmt.Println(err)
return
}
fmt.Printf("Received a Response: %s\n", string(m.Data))
time.Sleep(1 * time.Second)
}
}

View File

@ -0,0 +1,26 @@
package main
import (
"fmt"
"sync"
"github.com/nats-io/nats.go"
)
func main() {
nc, err := nats.Connect(nats.DefaultURL)
defer nc.Close()
if nil != err {
fmt.Println(err)
return
}
wg := sync.WaitGroup{}
wg.Add(10)
nc.Subscribe("foo", func(m *nats.Msg) {
fmt.Printf("Received a message: %s\n", string(m.Data))
m.Respond(m.Data)
wg.Done()
})
wg.Wait()
}

View File

@ -0,0 +1,25 @@
package main
import (
"fmt"
"sync"
"github.com/nats-io/nats.go"
)
func main() {
nc, err := nats.Connect(nats.DefaultURL)
defer nc.Close()
if nil != err {
fmt.Println(err)
return
}
wg := sync.WaitGroup{}
wg.Add(10)
nc.Subscribe("foo", func(m *nats.Msg) {
fmt.Printf("Received a message: %s\n", string(m.Data))
wg.Done()
})
wg.Wait()
}