Skip to main content

Nacos

This chapter contains nacos usage examples.

Introduction

The nacos component is a secondary encapsulation of nacos-group/nacos-sdk-go/v2. This component encapsulates some of the most commonly used methods, such as obtaining configuration, monitoring configuration, registering services, uninstalling services, obtaining healthy instances, etc.

Usage

Initial client

main.go
import (
"github.com/keepchen/go-sail/v3/lib/nacos"
)

func main() {
nacos.InitClient("appName", "endpoints", "namespace id")
}

Get configuration

main.go
import (
"github.com/keepchen/go-sail/v3/lib/nacos"
sailConfig "github.com/keepchen/go-sail/v3/sail/config"
)

func main() {
var conf = &sailConfig.Config{}
err := nacos.GetConfig(group, dataID, conf, "yaml")
}

Listen configuration

main.go
import (
"github.com/keepchen/go-sail/v3/lib/nacos"
sailConfig "github.com/keepchen/go-sail/v3/sail/config"
)

func main() {
var conf = &sailConfig.Config{}
callback := func(namespace, group, dataId, data string) {
err = nacos.ParseConfig([]byte(data), conf, "yaml")
if err != nil {
fmt.Printf("<Nacos> listen config {%s:%s} change,but can't be unmarshal: %s\n", group, dataId, err.Error())
return
}
}

//listen config if it changed
err = nacos.ListenConfigWithCallback(group, dataID, callback)
if err != nil {
panic(err)
}
}

Register service

main.go
import (
"github.com/keepchen/go-sail/v3/lib/nacos"
)

func main() {
ok, err := nacos.RegisterService(groupName, serviceName, ip, port, metadata)
}

Unregister service

main.go
import (
"github.com/keepchen/go-sail/v3/lib/nacos"
)

func main() {
ok, err := nacos.UnregisterService(groupName, serviceName, ip, port)
}

Get healthy instance

main.go
import (
"github.com/keepchen/go-sail/v3/lib/nacos"
)

func main() {
serviceUrl := nacos.GetHealthyInstanceUrl(group, serviceName, sail.GetLogger())
if len(serviceUrl) == 0 {
sail.GetLogger().Warn("no healthy instances")
return ""
}
}

Others

For more native calling methods, please view the official documentation of nacos-group/nacos-sdk-go/v2.