go?集成nacos注冊中心、配置中心的過程詳解
使用限制
Go>=v1.15
Nacos>2.x
安裝
使用go get安裝SDK:
go get -u github.com/nacos-group/nacos-sdk-go/v2
快速使用
初始化客戶端配置ClientConfig
constant.ClientConfig{
TimeoutMs uint64 // 請求Nacos服務(wù)端的超時時間,默認是10000ms
NamespaceId string // Nacos的命名空間Id
Endpoint string // 當(dāng)使用地址服務(wù)器時,需要該配置. https://help.aliyun.com/document_detail/130146.html
RegionId string // Nacos&KMS的regionId,用于配置中心的鑒權(quán)
AccessKey string // Nacos&KMS的AccessKey,用于配置中心的鑒權(quán)
SecretKey string // Nacos&KMS的SecretKey,用于配置中心的鑒權(quán)
OpenKMS bool // 是否開啟kms,默認不開啟,kms可以參考文檔 https://help.aliyun.com/product/28933.html
// 同時DataId必須以"cipher-"作為前綴才會啟動加解密邏輯
CacheDir string // 緩存service信息的目錄,默認是當(dāng)前運行目錄
UpdateThreadNum int // 監(jiān)聽service變化的并發(fā)數(shù),默認20
NotLoadCacheAtStart bool // 在啟動的時候不讀取緩存在CacheDir的service信息
UpdateCacheWhenEmpty bool // 當(dāng)service返回的實例列表為空時,不更新緩存,用于推空保護
Username string // Nacos服務(wù)端的API鑒權(quán)Username
Password string // Nacos服務(wù)端的API鑒權(quán)Password
LogDir string // 日志存儲路徑
RotateTime string // 日志輪轉(zhuǎn)周期,比如:30m, 1h, 24h, 默認是24h
MaxAge int64 // 日志最大文件數(shù),默認3
LogLevel string // 日志默認級別,值必須是:debug,info,warn,error,默認值是info
}ServerConfig
constant.ServerConfig{
ContextPath string // Nacos的ContextPath,默認/nacos,在2.0中不需要設(shè)置
IpAddr string // Nacos的服務(wù)地址
Port uint64 // Nacos的服務(wù)端口
Scheme string // Nacos的服務(wù)地址前綴,默認http,在2.0中不需要設(shè)置
GrpcPort uint64 // Nacos的 grpc 服務(wù)端口, 默認為 服務(wù)端口+1000, 不是必填
}Note:我們可以配置多個ServerConfig,客戶端會對這些服務(wù)端做輪詢請求
Create client
// 創(chuàng)建clientConfig
clientConfig := constant.ClientConfig{
NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468", // 如果需要支持多namespace,我們可以創(chuàng)建多個client,它們有不同的NamespaceId。當(dāng)namespace是public時,此處填空字符串。
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "/tmp/nacos/log",
CacheDir: "/tmp/nacos/cache",
LogLevel: "debug",
}
// 創(chuàng)建clientConfig的另一種方式
clientConfig := *constant.NewClientConfig(
constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"), //當(dāng)namespace是public時,此處填空字符串。
constant.WithTimeoutMs(5000),
constant.WithNotLoadCacheAtStart(true),
constant.WithLogDir("/tmp/nacos/log"),
constant.WithCacheDir("/tmp/nacos/cache"),
constant.WithLogLevel("debug"),
)
// 至少一個ServerConfig
serverConfigs := []constant.ServerConfig{
{
IpAddr: "console1.nacos.io",
ContextPath: "/nacos",
Port: 80,
Scheme: "http",
},
{
IpAddr: "console2.nacos.io",
ContextPath: "/nacos",
Port: 80,
Scheme: "http",
},
}
// 創(chuàng)建serverConfig的另一種方式
serverConfigs := []constant.ServerConfig{
*constant.NewServerConfig(
"console1.nacos.io",
80,
constant.WithScheme("http"),
constant.WithContextPath("/nacos"),
),
*constant.NewServerConfig(
"console2.nacos.io",
80,
constant.WithScheme("http"),
constant.WithContextPath("/nacos"),
),
}
// 創(chuàng)建服務(wù)發(fā)現(xiàn)客戶端
_, _ := clients.CreateNamingClient(map[string]interface{}{
"serverConfigs": serverConfigs,
"clientConfig": clientConfig,
})
// 創(chuàng)建動態(tài)配置客戶端
_, _ := clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": serverConfigs,
"clientConfig": clientConfig,
})
// 創(chuàng)建服務(wù)發(fā)現(xiàn)客戶端的另一種方式 (推薦)
namingClient, err := clients.NewNamingClient(
vo.NacosClientParam{
ClientConfig: &clientConfig,
ServerConfigs: serverConfigs,
},
)
// 創(chuàng)建動態(tài)配置客戶端的另一種方式 (推薦)
configClient, err := clients.NewConfigClient(
vo.NacosClientParam{
ClientConfig: &clientConfig,
ServerConfigs: serverConfigs,
},
)服務(wù)發(fā)現(xiàn)
注冊實例:RegisterInstance
success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
Ip: "10.0.0.11",
Port: 8848,
ServiceName: "demo.go",
Weight: 10,
Enable: true,
Healthy: true,
Ephemeral: true,
Metadata: map[string]string{"idc":"shanghai"},
ClusterName: "cluster-a", // 默認值DEFAULT
GroupName: "group-a", // 默認值DEFAULT_GROUP
})注銷實例:DeregisterInstance
success, err := namingClient.DeregisterInstance(vo.DeregisterInstanceParam{
Ip: "10.0.0.11",
Port: 8848,
ServiceName: "demo.go",
Ephemeral: true,
Cluster: "cluster-a", // 默認值DEFAULT
GroupName: "group-a", // 默認值DEFAULT_GROUP
})獲取服務(wù)信息:GetService
services, err := namingClient.GetService(vo.GetServiceParam{
ServiceName: "demo.go",
Clusters: []string{"cluster-a"}, // 默認值DEFAULT
GroupName: "group-a", // 默認值DEFAULT_GROUP
})獲取所有的實例列表:SelectAllInstances
// SelectAllInstance可以返回全部實例列表,包括healthy=false,enable=false,weight<=0
instances, err := namingClient.SelectAllInstances(vo.SelectAllInstancesParam{
ServiceName: "demo.go",
GroupName: "group-a", // 默認值DEFAULT_GROUP
Clusters: []string{"cluster-a"}, // 默認值DEFAULT
})獲取實例列表 :SelectInstances
// SelectInstances 只返回滿足這些條件的實例列表:healthy=${HealthyOnly},enable=true 和weight>0
instances, err := namingClient.SelectInstances(vo.SelectInstancesParam{
ServiceName: "demo.go",
GroupName: "group-a", // 默認值DEFAULT_GROUP
Clusters: []string{"cluster-a"}, // 默認值DEFAULT
HealthyOnly: true,
})獲取一個健康的實例(加權(quán)隨機輪詢):SelectOneHealthyInstance
// SelectOneHealthyInstance將會按加權(quán)隨機輪詢的負載均衡策略返回一個健康的實例
// 實例必須滿足的條件:health=true,enable=true and weight>0
instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
ServiceName: "demo.go",
GroupName: "group-a", // 默認值DEFAULT_GROUP
Clusters: []string{"cluster-a"}, // 默認值DEFAULT
})監(jiān)聽服務(wù)變化:Subscribe
// Subscribe key=serviceName+groupName+cluster
// 注意:我們可以在相同的key添加多個SubscribeCallback.
err := namingClient.Subscribe(vo.SubscribeParam{
ServiceName: "demo.go",
GroupName: "group-a", // 默認值DEFAULT_GROUP
Clusters: []string{"cluster-a"}, // 默認值DEFAULT
SubscribeCallback: func(services []model.Instance, err error) {
log.Printf("\n\n callback return services:%s \n\n", utils.ToJsonString(services))
},
})取消服務(wù)監(jiān)聽:Unsubscribe
err := namingClient.Unsubscribe(vo.SubscribeParam{
ServiceName: "demo.go",
GroupName: "group-a", // 默認值DEFAULT_GROUP
Clusters: []string{"cluster-a"}, // 默認值DEFAULT
SubscribeCallback: func(services []model.Instance, err error) {
log.Printf("\n\n callback return services:%s \n\n", utils.ToJsonString(services))
},
})獲取服務(wù)名列表
serviceInfos, err := namingClient.GetAllServicesInfo(vo.GetAllServiceInfoParam{
NameSpace: "0e83cc81-9d8c-4bb8-a28a-ff703187543f",
PageNo: 1,
PageSize: 10,
}),動態(tài)配置
發(fā)布配置:PublishConfig
success, err := configClient.PublishConfig(vo.ConfigParam{
DataId: "dataId",
Group: "group",
Content: "hello world!222222"})刪除配置:DeleteConfig
success, err = configClient.DeleteConfig(vo.ConfigParam{
DataId: "dataId",
Group: "group"})獲取配置:GetConfig
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: "dataId",
Group: "group"})監(jiān)聽配置變化:ListenConfig
err := configClient.ListenConfig(vo.ConfigParam{
DataId: "dataId",
Group: "group",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
},
})取消配置監(jiān)聽:CancelListenConfig
err := configClient.CancelListenConfig(vo.ConfigParam{
DataId: "dataId",
Group: "group",
})搜索配置: SearchConfig
configPage,err := configClient.SearchConfig(vo.SearchConfigParam{
Search: "blur",
DataId: "",
Group: "",
PageNo: 1,
PageSize: 10,
})工具
client
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nacos
import (
"fmt"
"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
"github.com/nacos-group/nacos-sdk-go/v2/vo"
)
func RegisterServiceInstance(client naming_client.INamingClient, param vo.RegisterInstanceParam) {
success, err := client.RegisterInstance(param)
if !success || err != nil {
panic("RegisterServiceInstance failed!" + err.Error())
}
fmt.Printf("RegisterServiceInstance,param:%+v,result:%+v \n\n", param, success)
}
func BatchRegisterServiceInstance(client naming_client.INamingClient, param vo.BatchRegisterInstanceParam) {
success, err := client.BatchRegisterInstance(param)
if !success || err != nil {
panic("BatchRegisterServiceInstance failed!" + err.Error())
}
fmt.Printf("BatchRegisterServiceInstance,param:%+v,result:%+v \n\n", param, success)
}
func DeRegisterServiceInstance(client naming_client.INamingClient, param vo.DeregisterInstanceParam) {
success, err := client.DeregisterInstance(param)
if !success || err != nil {
panic("DeRegisterServiceInstance failed!" + err.Error())
}
fmt.Printf("DeRegisterServiceInstance,param:%+v,result:%+v \n\n", param, success)
}
func UpdateServiceInstance(client naming_client.INamingClient, param vo.UpdateInstanceParam) {
success, err := client.UpdateInstance(param)
if !success || err != nil {
panic("UpdateInstance failed!" + err.Error())
}
fmt.Printf("UpdateServiceInstance,param:%+v,result:%+v \n\n", param, success)
}
func GetService(client naming_client.INamingClient, param vo.GetServiceParam) {
service, err := client.GetService(param)
if err != nil {
panic("GetService failed!" + err.Error())
}
fmt.Printf("GetService,param:%+v, result:%+v \n\n", param, service)
}
func SelectAllInstances(client naming_client.INamingClient, param vo.SelectAllInstancesParam) {
instances, err := client.SelectAllInstances(param)
if err != nil {
panic("SelectAllInstances failed!" + err.Error())
}
fmt.Printf("SelectAllInstance,param:%+v, result:%+v \n\n", param, instances)
}
func SelectInstances(client naming_client.INamingClient, param vo.SelectInstancesParam) {
instances, err := client.SelectInstances(param)
if err != nil {
panic("SelectInstances failed!" + err.Error())
}
fmt.Printf("SelectInstances,param:%+v, result:%+v \n\n", param, instances)
}
func SelectOneHealthyInstance(client naming_client.INamingClient, param vo.SelectOneHealthInstanceParam) {
instances, err := client.SelectOneHealthyInstance(param)
if err != nil {
panic("SelectOneHealthyInstance failed!")
}
fmt.Printf("SelectOneHealthyInstance,param:%+v, result:%+v \n\n", param, instances)
}
func Subscribe(client naming_client.INamingClient, param *vo.SubscribeParam) {
_ = client.Subscribe(param)
}
func UnSubscribe(client naming_client.INamingClient, param *vo.SubscribeParam) {
_ = client.Unsubscribe(param)
}
func GetAllService(client naming_client.INamingClient, param vo.GetAllServiceInfoParam) {
service, err := client.GetAllServicesInfo(param)
if err != nil {
panic("GetAllService failed!")
}
fmt.Printf("GetAllService,param:%+v, result:%+v \n\n", param, service)
}config
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nacos
import (
"fmt"
"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
"github.com/nacos-group/nacos-sdk-go/v2/model"
"github.com/nacos-group/nacos-sdk-go/v2/vo"
)
func PublishConfig(client config_client.IConfigClient, param vo.ConfigParam) {
//publish config
//config key=dataId+group+namespaceId
_, err := client.PublishConfig(param)
if err != nil {
fmt.Printf("PublishConfig err:%+v \n", err)
}
}
func DeleteConfig(client config_client.IConfigClient, param vo.ConfigParam) {
_, err := client.DeleteConfig(param)
if err != nil {
fmt.Printf("DeleteConfig err:%+v \n", err)
}
}
func GetConfig(client config_client.IConfigClient, param vo.ConfigParam) string {
//get config
content, err := client.GetConfig(param)
if err != nil {
fmt.Printf("GetConfig err:%+v \n", err)
} else {
fmt.Println("GetConfig,config :" + content)
}
return content
}
func ListenConfig(client config_client.IConfigClient, param vo.ConfigParam) {
//Listen config change,key=dataId+group+namespaceId.
err := client.ListenConfig(vo.ConfigParam{
DataId: "test-data",
Group: "test-group",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("config changed group:" + group + ", dataId:" + dataId + ", content:" + data)
},
})
if err != nil {
fmt.Printf("PublishConfig err:%+v \n", err)
}
}
func CancelListenConfig(client config_client.IConfigClient, param vo.ConfigParam) {
//cancel config change
err := client.CancelListenConfig(param)
if err != nil {
fmt.Printf("CancelListenConfig err:%+v \n", err)
}
}
func SearchConfig(client config_client.IConfigClient, param vo.SearchConfigParam) *model.ConfigPage {
searchPage, err := client.SearchConfig(param)
if err != nil {
fmt.Printf("SearchConfig err:%+v \n", err)
} else {
fmt.Printf("SearchConfig:%+v \n", searchPage)
}
return searchPage
}到此這篇關(guān)于go 集成nacos注冊中心、配置中心的文章就介紹到這了,更多相關(guān)go 集成nacos內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語言并發(fā)處理效率響應(yīng)能力及在現(xiàn)代軟件開發(fā)中的重要性
這篇文章主要為大家介紹了Go語言并發(fā)處理的效率及響應(yīng)能力以及在現(xiàn)代軟件開發(fā)中的重要性實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
golang開發(fā)?gorilla?websocket的使用示例詳解
這篇文章主要介紹了golang開發(fā)?gorilla?websocket的使用示例詳解,介紹了websocket的簡單使用,我們使用的版本是1.3.0,具體操作方法跟隨小編一起學(xué)習(xí)吧2024-05-05
四種Golang實現(xiàn)middleware框架的方式小結(jié)
middleware是一般框架里面常用的形式,比如web框架、rpc框架等,本文為大家詳細介紹了四種實現(xiàn)middleawre的方式,感興趣的可以了解一下2024-03-03
Golang?實現(xiàn)Redis?協(xié)議解析器的解決方案
這篇文章主要介紹了Golang???實現(xiàn)?Redis?協(xié)議解析器,本文將分別介紹Redis 通信協(xié)議 以及 協(xié)議解析器 的實現(xiàn),若您對協(xié)議有所了解可以直接閱讀協(xié)議解析器部分,需要的朋友可以參考下2022-10-10
Go語言配置數(shù)據(jù)庫連接池的實現(xiàn)
本文內(nèi)容我們將解釋連接池背后是如何工作的,并探索如何配置數(shù)據(jù)庫能改變或優(yōu)化其性能。文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12

