NATS初步学习

服务端

package main

import (
        "fmt"

        "github.com/nats-io/nats-server/v2/server"
        "go.uber.org/automaxprocs/maxprocs"
)

func main() {
        exe := "nats-server"

        opts := DefaultOptions()

        // Create the server with appropriate options.
        s, err := server.NewServer(opts)
        if err != nil {
                server.PrintAndDie(fmt.Sprintf("%s: %s", exe, err))
        }

        // Configure the logger based on the flags
        s.ConfigureLogger()

        // Start things up. Block here until done.
        if err := server.Run(s); err != nil {
                server.PrintAndDie(err.Error())
        }

        // Adjust MAXPROCS if running under linux/cgroups quotas.
        undo, err := maxprocs.Set(maxprocs.Logger(s.Debugf))
        if err != nil {
                s.Warnf("Failed to set GOMAXPROCS: %v", err)
        } else {
                defer undo()
        }

        s.WaitForShutdown()
}

func DefaultOptions() *server.Options {
        return &server.Options{
                Host:     "127.0.0.1",
                Port:     4222,
                HTTPPort: -1,
                Cluster:  server.ClusterOpts{Port: -1, Name: "abc"},
                NoLog:    false,
                NoSigs:   true,
                Debug:    true,
                Trace:    true,
        }
}

发布者

package main

import (
        "fmt"
        "time"

        "github.com/nats-io/nats.go"
)

func main() {
        nc, _ := nats.Connect(nats.DefaultURL)
        // nc.Publish("ncp.foo", []byte("Boos升级"))

        nc.Subscribe("ncp.foo.response", func(msg *nats.Msg) {
                fmt.Println("---> 收到, ", string(msg.Data))
        })
        msg, err := nc.Request("ncp.foo", []byte("砍瓜切菜"), time.Second*30)
        if err != nil {
                panic(err)
        }
        fmt.Println(string(msg.Data))
        nc.Close()
}

订阅者

package main

import (
        "fmt"
        "os"
        "os/signal"
        "syscall"

        "github.com/nats-io/nats.go"
)

var (
        nc *nats.Conn
)

func Handler_Foo(msg *nats.Msg) {
        fmt.Println(string(msg.Data))

        fmt.Println(msg.Subject, msg.Reply)
        nc.Publish(msg.Reply, []byte("我收到你的消息了,"+string(msg.Data)))

        fmt.Println(msg.Subject, msg.Reply)
        msg.Reply = "ncp.foo.response"
        msg.Respond([]byte("我收到了,笋," + string(msg.Data)))

}

func GraceExit() {
        fmt.Println("退出")
}

func main() {
        nc, _ = nats.Connect(nats.DefaultURL)

        nc.Subscribe("ncp.foo", Handler_Foo)

        // 阻塞,收到系统信号退出
        sigs := make(chan os.Signal, 1)
        signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
        <-sigs
        GraceExit()
        nc.Close()
}
posted @ 2023-06-29 16:19  jiftle  阅读(44)  评论(0编辑  收藏  举报