根据需要GO 项目也接入Nacos
系统版本:Linux 5.4.18-87.76-generic KYLINOS SMP Thu Aug 31 09:05:44 UTC 2023 aarch64 aarch64 aarch64 GNU/Linux
Go:1.19.4
1.查看Nacos-sdk-go 官方适配自己的工程
github.com/nacos-group/nacos-sdk-go
NacosManager.go
package main
import (
"fmt"
"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/vo"
"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
)
type Client struct {
Ip string
Port int
ServiceName string
GroupName string
ClusterName string
NacosAddr string
NacosPort uint64
conn naming_client.INamingClient
}
func NewClient() IClient {
c := &Client{
Ip: "127.0.0.1",
Port: 9527,
ServiceName: "Test-Nacos-go",
GroupName :"DEFAULT_GROUP",
ClusterName:"DefaultCluster",
NacosAddr: "127.0.0.1",
NacosPort: 8848,
}
//create ServerConfig
sc := []constant.ServerConfig{
*constant.NewServerConfig(c.NacosAddr, c.NacosPort, constant.WithContextPath("/nacos")),
}
//create ClientConfig
cc := *constant.NewClientConfig(
constant.WithNamespaceId("Test-Nacos"),
constant.WithTimeoutMs(5000),
constant.WithNotLoadCacheAtStart(true),
constant.WithLogDir("/tmp/nacos/log"),
constant.WithCacheDir("/tmp/nacos/cache"),
constant.WithLogLevel("debug"),
)
// create naming client
ct, err := clients.NewNamingClient(
vo.NacosClientParam{
ClientConfig: &cc,
ServerConfigs: sc,
},
)
if err != nil {
panic(err)
}
c.conn=ct
return c
}
func (c *Client) Start() {
go func() {
//Register
registerServiceInstance(c.conn, vo.RegisterInstanceParam{
Ip: "127.0.0.1",
Port: 9527,
ServiceName: "Test-Nacos-go",
GroupName: "DEFAULT_GROUP",
ClusterName: "DefaultCluster",
Weight: 10,
Enable: true,
Healthy: true,
Ephemeral: true,
Metadata: map[string]string{"test": "test"},
})
select { }
}()
}
func (c *Client) Stop() {
//DeRegister
deRegisterServiceInstance(c.conn, vo.DeregisterInstanceParam{
Ip: "127.0.0.1",
Port: 9527,
ServiceName: "Test-Nacos-go",
GroupName: "DEFAULT_GROUP",
Cluster: "DefaultCluster",
Ephemeral: true, //it must be true
})
}
func registerServiceInstance(clientNacos naming_client.INamingClient, param vo.RegisterInstanceParam) {
success, err := clientNacos.RegisterInstance(param)
if !success || err != nil {
panic("RegisterServiceInstance failed!" + err.Error())
}
fmt.Printf("RegisterServiceInstance,param:%+v,result:%+v \n\n", param, success)
}
func deRegisterServiceInstance(clientNacos naming_client.INamingClient, param vo.DeregisterInstanceParam) {
success, err := clientNacos.DeregisterInstance(param)
if !success || err != nil {
panic("DeRegisterServiceInstance failed!" + err.Error())
}
fmt.Printf("DeRegisterServiceInstance,param:%+v,result:%+v \n\n", param, success)
}
2.接口层
IClient.go
package main
type IClient interface {
Start()
Stop()
}
3.服务集成
TestNacos.go
package main
import (
"net/http"
"fmt"
"time"
)
func HelloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("<h1>Hello World</h1>"))
}
func HttpRootHandler(w http.ResponseWriter, r *http.Request) {
time_fmt := "2006-01-02 15:04:05"
local_time := time.Now().Local()
time_str := local_time.Format(time_fmt)
ret_str := fmt.Sprintf("{\"msg\":\"Hello, Nacos-Go! Nacos Service start!\", \"time\":\"%s\"}", time_str)
w.Header().Set("Content-Type", "application/json;charset=utf-8")
w.Write([]byte(ret_str))
return
}
func initNacos(){
client := NewClient()
go client.Start()
}
func main() {
initNacos()
http.HandleFunc("/test", HttpRootHandler)
http.HandleFunc("/hello", HelloHandler)
// 启动一个Web服务,并监听9527端口
http.ListenAndServe(":9527",nil)
}
4.编译
go run TestNacos.go NacosManager.go IClient.go
因为只是测试程序,没有写工程,所以编译的时候需要将依赖的文件全部加入。
5.运行