增加 NATS Golang Client 示例代码. #8

Merged
lion187 merged 1 commits from dev into master 2021-06-29 16:07:31 +08:00
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()
}