Limitations of use
Go>=v1.15
Nacos>
Install
usego get
Install the SDK:
go get -u /nacos-group/nacos-sdk-go/v2
Quick use
Initialize client configuration ClientConfig
{ TimeoutMs uint64 // The timeout time for requesting Nacos server is 10000ms by default NamespaceId string // Nacos namespace Id Endpoint string // This configuration is required when using the address server. /document_detail/ RegionId string // Nacos&KMS regionId is used to configure the authentication center AccessKey string // Nacos&KMS's AccessKey is used to configure the authentication center SecretKey string // Nacos&KMS's SecretKey is used to authenticate the configuration center OpenKMS bool // Whether to enable kms, it is not enabled by default. You can refer to the document /product/ // At the same time, DataId must be prefixed with "cipher-" to start the encryption and decryption logic CacheDir string // The directory where service information is cached, the default is the current running directory UpdateThreadNum int // The number of concurrency listens to the service changes, default is 20 NotLoadCacheAtStart bool // Do not read service information cached in CacheDir during startup UpdateCacheWhenEmpty bool // When the instance list returned by the service is empty, the cache is not updated, and it is used to push the empty protection Username string // Username of the API authentication of Nacos server Password string // Password of the Nacos server API authentication LogDir string // Log storage path RotateTime string // Log rotation period, for example: 30m, 1h, 24h, default is 24h MaxAge int64 // Maximum number of log files, default 3 LogLevel string // The default level of the log must be: debug, info, warn, error, the default value is info}
ServerConfig
{ ContextPath string // Nacos' ContextPath, default /nacos, does not need to be set in 2.0 IpAddr string //Nacos service address Port uint64 //Nacos service port Scheme string // Nacos' service address prefix, default http, no need to set it in 2.0 GrpcPort uint64 // Nacos' grpc service port, default is service port +1000, not required}
Note: We can configure multiple ServerConfigs, and the client will poll and request these servers.
Create client
// Create clientConfigclientConfig := { NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468", // If you need to support multiple namespaces, we can create multiple clients, and they have different NamespaceIds. When namespace is public, fill in the blank string here. TimeoutMs: 5000, NotLoadCacheAtStart: true, LogDir: "/tmp/nacos/log", CacheDir: "/tmp/nacos/cache", LogLevel: "debug", } // Another way to create clientConfigclientConfig := *( ("e525eafa-f7d7-4029-83d9-008937f9d468"), //When namespace is public, fill in the blank string here. (5000), (true), ("/tmp/nacos/log"), ("/tmp/nacos/cache"), ("debug"), ) // At least one ServerConfigserverConfigs := []{ { IpAddr: "", ContextPath: "/nacos", Port: 80, Scheme: "http", }, { IpAddr: "", ContextPath: "/nacos", Port: 80, Scheme: "http", }, } // Another way to create serverConfigserverConfigs := []{ *( "", 80, ("http"), ("/nacos"), ), *( "", 80, ("http"), ("/nacos"), ), } // Create a service discovery client_, _ := (map[string]interface{}{ "serverConfigs": serverConfigs, "clientConfig": clientConfig, }) // Create dynamic configuration client_, _ := (map[string]interface{}{ "serverConfigs": serverConfigs, "clientConfig": clientConfig, }) // Another way to create a service discovery client (recommended)namingClient, err := ( { ClientConfig: &clientConfig, ServerConfigs: serverConfigs, }, ) // Another way to create dynamic configuration clients (recommended)configClient, err := ( { ClientConfig: &clientConfig, ServerConfigs: serverConfigs, }, )
Service Discovery
RegisterInstance
success, err := ({ Ip: "10.0.0.11", Port: 8848, ServiceName: "", Weight: 10, Enable: true, Healthy: true, Ephemeral: true, Metadata: map[string]string{"idc":"shanghai"}, ClusterName: "cluster-a", // Default value DEFAULT GroupName: "group-a", // Default value DEFAULT_GROUP})
Logout instance: DeregisterInstance
success, err := ({ Ip: "10.0.0.11", Port: 8848, ServiceName: "", Ephemeral: true, Cluster: "cluster-a", // Default value DEFAULT GroupName: "group-a", // Default value DEFAULT_GROUP})
Get service information: GetService
services, err := ({ ServiceName: "", Clusters: []string{"cluster-a"}, // Default value DEFAULT GroupName: "group-a", // Default value DEFAULT_GROUP})
Get a list of all instances: SelectAllInstances
// SelectAllInstance can return a list of all instances, including healthy=false, enable=false, weight<=0instances, err := ({ ServiceName: "", GroupName: "group-a", // Default value DEFAULT_GROUP Clusters: []string{"cluster-a"}, // Default value DEFAULT})
Get the list of instances: SelectInstances
// SelectInstances only returns a list of instances that meet these conditions: healthy=${HealthyOnly}, enable=true and weight>0instances, err := ({ ServiceName: "", GroupName: "group-a", // Default value DEFAULT_GROUP Clusters: []string{"cluster-a"}, // Default value DEFAULT HealthyOnly: true, })
Get a healthy instance (weighted random polling): SelectOneHealthyInstance
// SelectOneHealthyInstance will return a healthy instance according to the load balancing policy with weighted random polling// The conditions that the instance must meet: health=true,enable=true and weight>0instance, err := ({ ServiceName: "", GroupName: "group-a", // Default value DEFAULT_GROUP Clusters: []string{"cluster-a"}, // Default value DEFAULT})
Listening service changes: Subscribe
// Subscribe key=serviceName+groupName+cluster // Note: We can add multiple SubscribeCallbacks to the same key.err := ({ ServiceName: "", GroupName: "group-a", // Default value DEFAULT_GROUP Clusters: []string{"cluster-a"}, // Default value DEFAULT SubscribeCallback: func(services [], err error) { ("\n\n callback return services:%s \n\n", (services)) }, })
Cancel service listening: Unsubscribe
err := ({ ServiceName: "", GroupName: "group-a", // Default value DEFAULT_GROUP Clusters: []string{"cluster-a"}, // Default value DEFAULT SubscribeCallback: func(services [], err error) { ("\n\n callback return services:%s \n\n", (services)) }, })
Get the service name list
serviceInfos, err := ({ NameSpace: "0e83cc81-9d8c-4bb8-a28a-ff703187543f", PageNo: 1, PageSize: 10, }),
Dynamic configuration
PublishConfig
success, err := ({ DataId: "dataId", Group: "group", Content: "hello world!222222"})
DeleteConfig
success, err = ({ DataId: "dataId", Group: "group"})
Get Configuration: GetConfig
content, err := ({ DataId: "dataId", Group: "group"})
ListenConfig
err := ({ DataId: "dataId", Group: "group", OnChange: func(namespace, group, dataId, data string) { ("group:" + group + ", dataId:" + dataId + ", data:" + data) }, })
CancelListenConfig
err := ({ DataId: "dataId", Group: "group", })
SearchConfig
configPage,err := ({ Search: "blur", DataId: "", Group: "", PageNo: 1, PageSize: 10, })
tool
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 * * /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" "/nacos-group/nacos-sdk-go/v2/clients/naming_client" "/nacos-group/nacos-sdk-go/v2/vo" ) func RegisterServiceInstance(client naming_client.INamingClient, param ) { success, err := (param) if !success || err != nil { panic("RegisterServiceInstance failed!" + ()) } ("RegisterServiceInstance,param:%+v,result:%+v \n\n", param, success) } func BatchRegisterServiceInstance(client naming_client.INamingClient, param ) { success, err := (param) if !success || err != nil { panic("BatchRegisterServiceInstance failed!" + ()) } ("BatchRegisterServiceInstance,param:%+v,result:%+v \n\n", param, success) } func DeRegisterServiceInstance(client naming_client.INamingClient, param ) { success, err := (param) if !success || err != nil { panic("DeRegisterServiceInstance failed!" + ()) } ("DeRegisterServiceInstance,param:%+v,result:%+v \n\n", param, success) } func UpdateServiceInstance(client naming_client.INamingClient, param ) { success, err := (param) if !success || err != nil { panic("UpdateInstance failed!" + ()) } ("UpdateServiceInstance,param:%+v,result:%+v \n\n", param, success) } func GetService(client naming_client.INamingClient, param ) { service, err := (param) if err != nil { panic("GetService failed!" + ()) } ("GetService,param:%+v, result:%+v \n\n", param, service) } func SelectAllInstances(client naming_client.INamingClient, param ) { instances, err := (param) if err != nil { panic("SelectAllInstances failed!" + ()) } ("SelectAllInstance,param:%+v, result:%+v \n\n", param, instances) } func SelectInstances(client naming_client.INamingClient, param ) { instances, err := (param) if err != nil { panic("SelectInstances failed!" + ()) } ("SelectInstances,param:%+v, result:%+v \n\n", param, instances) } func SelectOneHealthyInstance(client naming_client.INamingClient, param ) { instances, err := (param) if err != nil { panic("SelectOneHealthyInstance failed!") } ("SelectOneHealthyInstance,param:%+v, result:%+v \n\n", param, instances) } func Subscribe(client naming_client.INamingClient, param *) { _ = (param) } func UnSubscribe(client naming_client.INamingClient, param *) { _ = (param) } func GetAllService(client naming_client.INamingClient, param ) { service, err := (param) if err != nil { panic("GetAllService failed!") } ("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 * * /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" "/nacos-group/nacos-sdk-go/v2/clients/config_client" "/nacos-group/nacos-sdk-go/v2/model" "/nacos-group/nacos-sdk-go/v2/vo" ) func PublishConfig(client config_client.IConfigClient, param ) { //publish config //config key=dataId+group+namespaceId _, err := (param) if err != nil { ("PublishConfig err:%+v \n", err) } } func DeleteConfig(client config_client.IConfigClient, param ) { _, err := (param) if err != nil { ("DeleteConfig err:%+v \n", err) } } func GetConfig(client config_client.IConfigClient, param ) string { //get config content, err := (param) if err != nil { ("GetConfig err:%+v \n", err) } else { ("GetConfig,config :" + content) } return content } func ListenConfig(client config_client.IConfigClient, param ) { //Listen config change,key=dataId+group+namespaceId. err := ({ DataId: "test-data", Group: "test-group", OnChange: func(namespace, group, dataId, data string) { ("config changed group:" + group + ", dataId:" + dataId + ", content:" + data) }, }) if err != nil { ("PublishConfig err:%+v \n", err) } } func CancelListenConfig(client config_client.IConfigClient, param ) { //cancel config change err := (param) if err != nil { ("CancelListenConfig err:%+v \n", err) } } func SearchConfig(client config_client.IConfigClient, param ) * { searchPage, err := (param) if err != nil { ("SearchConfig err:%+v \n", err) } else { ("SearchConfig:%+v \n", searchPage) } return searchPage }
This is the article about Go Integrated Nacos Registration Center and Configuration Center. For more related Go Integrated Nacos content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!