nacos-sdk-go

repository·master·Indexed 23 days ago

https://github.com/nacos-group/nacos-sdk-go

A Go client for Nacos providing service discovery (naming) and dynamic configuration capabilities. It supports managing service instances via a Naming Client and configuration data via a Config Client, with integration options for Alibaba Cloud Application Configuration Management (ACM). Requires Go version >= v1.15 and Nacos version > 2.x.

Tokens
4.9K
Snippets
10
Records
13
Agent score
30%

What's inside nacos-sdk-go

  1. Create Naming and Config Clients

    master

    To interact with Nacos, you must create a Naming Client (for service discovery) and/or a Config Client (for dynamic configuration). The recommended way is to use the NewNamingClient and NewConfigClient functions with vo.NacosClientParam.

    // Create clientConfig
    clientConfig := constant.ClientConfig{
    	NamespaceId:         "e525eafa-f7d7-4029-83d9-008937f9d468",
    	TimeoutMs:           5000,
    	NotLoadCacheAtStart: true,
    	LogDir:              "/tmp/nacos/log",
    	CacheDir:            "/tmp/nacos/cache",
    	LogLevel:            "debug",
    }
    
    // At least one ServerConfig
    serverConfigs := []constant.ServerConfig{
    	{
    		IpAddr:      "console1.nacos.io",
    		ContextPath: "/nacos",
    		Port:        80,
    		Scheme:      "http",
    	},
    }
    
    // Create naming client for service discovery (recommended)
    namingClient, err := clients.NewNamingClient(
    	vo.NacosClientParam{
    		ClientConfig:  &clientConfig,
    		ServerConfigs: serverConfigs,
    	},
    )
    
    // Create config client for dynamic configuration (recommended)
    configClient, err := clients.NewConfigClient(
    	vo.NacosClientParam{
    		ClientConfig:  &clientConfig,
    		ServerConfigs: serverConfigs,
    	},
    )
  2. Configure ClientConfig

    master

    The constant.ClientConfig struct defines the client's behavior, authentication, and logging. Key fields include:

    • NamespaceId: The Nacos namespace ID. Use an empty string for the public namespace.
    • TimeoutMs: Request timeout in milliseconds (default: 10000ms).
    • Username / Password: Credentials for Nacos authentication.
    • CacheDir: Directory for persisting Nacos service info.
    • LogDir: Directory for logs.
    • LogLevel: Log level (debug, info, warn, error; default: info).
    • OpenKMS: Enables KMS (default: false).
    • Endpoint, RegionId, AccessKey, SecretKey: Used for ACM (Alibaba Cloud Application Configuration Management) integration.
    constant.ClientConfig {
    	TimeoutMs   uint64 // timeout for requesting Nacos server, default value is 10000ms
    	NamespaceId string // the namespaceId of Nacos
    	Endpoint    string // the endpoint for ACM. https://help.aliyun.com/document_detail/130146.html
    	RegionId    string // the regionId for ACM & KMS
    	AccessKey   string // the AccessKey for ACM & KMS
    	SecretKey   string // the SecretKey for ACM & KMS
    	OpenKMS     bool   // it's to open KMS, default is false. https://help.aliyun.com/product/28933.html
    	// , to enable encrypt/decrypt, DataId should be start with "cipher-"
    	CacheDir             string // the directory for persist nacos service info,default value is current path
    	UpdateThreadNum      int    // the number of goroutine for update nacos service info,default value is 20
    	NotLoadCacheAtStart  bool   // not to load persistent nacos service info in CacheDir at start time
    	UpdateCacheWhenEmpty bool   // update cache when get empty service instance from server
    	Username             string // the username for nacos auth
    	Password             string // the password for nacos auth
    	LogDir               string // the directory for log, default is current path
    	RotateTime           string // the rotate time for log, eg: 30m, 1h, 24h, default is 24h
    	MaxAge               int64  // the max age of a log file, default value is 3
    	LogLevel             string // the level of log, it's must be debug,info,warn,error, default value is info
    }
  3. Configure ClientConfig for Nacos

    master

    The constant.ClientConfig struct defines the connection and behavior settings for the Nacos client. Key fields include:

    • NamespaceId: The ACM namespace ID (use empty string for public).
    • TimeoutMs: Request timeout in milliseconds (default: 10000ms).
    • CacheDir: Directory for caching service information (default: current directory).
    • LogDir: Path for log storage.
    • LogLevel: Log level (debug, info, warn, error; default: info).
    • Username/Password: API authentication credentials.
    • OpenKMS: Enables KMS (requires DataId to have a cipher- prefix).
    • UpdateCacheWhenEmpty: If true, prevents updating cache when a service returns an empty instance list (push-empty protection).
  4. Configure ServerConfig for Nacos

    master

    The constant.ServerConfig struct defines the Nacos server connection details. You can provide multiple ServerConfig objects to enable client-side load balancing (polling) across servers.

    • IpAddr: Nacos server address.
    • Port: Nacos service port.
    • GrpcPort: Nacos gRPC service port (defaults to Port + 1000).
    • ContextPath: Nacos context path (default: /nacos; not required in 2.0+).
    • Scheme: Protocol prefix (default: http; not required in 2.0+).
  5. Configure ServerConfig

    master

    The constant.ServerConfig struct defines the Nacos server connection details. You can provide multiple ServerConfig objects to enable client-side rotation/load balancing across servers.

    • IpAddr: The Nacos server address.
    • Port: The Nacos server port.
    • GrpcPort: The Nacos gRPC port (defaults to server port + 1000).
    • Scheme: The server scheme (e.g., http).
    • ContextPath: The Nacos server context path (default: /nacos).
    constant.ServerConfig{
        Scheme      string // the nacos server scheme,defaut=http,this is not required in 2.0 
        ContextPath string // the nacos server contextpath,defaut=/nacos,this is not required in 2.0 
        IpAddr      string // the nacos server address 
        Port        uint64 // nacos server port
        GrpcPort    uint64 // nacos server grpc port, default=server port + 1000, this is not required
    }
  6. Create a Client for ACM

    master

    If you are using Alibaba Cloud Application Configuration Management (ACM), configure the ClientConfig with ACM-specific credentials and endpoints.

    cc := constant.ClientConfig{
    	Endpoint:    "acm.aliyun.com:8080",
    	NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468",
    	RegionId:    "cn-shanghai",
    	AccessKey:   "LTAI4G8KxxxxxxxxxxxxxbwZLBr",
    	SecretKey:   "n5jTL9YxxxxxxxxxxxxaxmPLZV9",
    	OpenKMS:     true,
    	TimeoutMs:   5000,
    	LogLevel:    "debug",
    }
    
    // Create config client for ACM
    client, err := clients.NewConfigClient(
    	vo.NacosClientParam{
    		ClientConfig: &cc,
    	},
    )
  7. Use Dynamic Configuration (Config Client)

    master

    The Config Client allows you to manage and listen to configuration data. Key operations include:

    • PublishConfig: Publish/update configuration content.
    • DeleteConfig: Delete a configuration.
    • GetConfig: Retrieve configuration content.
    • ListenConfig: Listen for changes to a specific configuration.
    • CancelListenConfig: Stop listening to a configuration.
    • SearchConfig: Search for configurations.
    // Publish config
    success, err := configClient.PublishConfig(vo.ConfigParam{
    	DataId: "dataId",
    	Group:  "group",
    	Content: "hello world!222222",
    })
    
    // Listen config change event
    err := configClient.ListenConfig(vo.ConfigParam{
    	DataId: "dataId",
    	Group:  "group",
    	OnChange: func (namespace, group, dataId, data string) {
    		fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
    	},
    })
    
    // Search config
    configPage, err := configClient.SearchConfig(vo.SearchConfigParam{
    	Search:   "blur",
    	DataId:   "",
    	Group:    "",
    	PageNo:   1,
    	PageSize: 10,
    })
  8. Manage Service Instances (Service Discovery)

    master

    Use the namingClient to perform the following service discovery tasks:

    • Register an instance: RegisterInstance(vo.RegisterInstanceParam)
    • Deregister an instance: DeregisterInstance(vo.DeregisterInstanceParam)
    • Get service info: GetService(vo.GetServiceParam)
    • Get all instances (including unhealthy/disabled): SelectAllInstances(vo.SelectAllInstancesParam)
    • Get healthy instances: SelectInstances(vo.SelectInstancesParam) (filters for healthy=true, enable=true, and weight>0).
    • Get one healthy instance (weighted random load balancing): SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam)
    • Subscribe to service changes: Subscribe(vo.SubscribeParam) (triggers a callback when service instances change).
    • Unsubscribe: Unsubscribe(vo.SubscribeParam).
    // Register an instance
    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",
        GroupName:   "group-a",
    })
    
    // Subscribe to service changes
    err := namingClient.Subscribe(vo.SubscribeParam{
        ServiceName: "demo.go",
        GroupName:   "group-a",
        Clusters:    []string{"cluster-a"},
        SubscribeCallback: func(services []model.Instance, err error) {
            log.Printf("callback return services:%s \n", utils.ToJsonString(services))
        },
    })
  9. Use Service Discovery (Naming Client)

    master

    The Naming Client allows you to manage service instances and discover services. Key operations include:

    • RegisterInstance: Register a service instance.
    • DeregisterInstance: Remove a service instance.
    • GetService: Retrieve service information.
    • SelectAllInstances: Get all instances (including unhealthy/disabled ones).
    • SelectInstances: Get instances filtered by health, enablement, and weight.
    • SelectOneHealthyInstance: Get a single healthy instance using the Weighted Round Robin (WRR) strategy.
    • Subscribe: Listen for service change events.
    • Unsubscribe: Stop listening for service change events.
    • GetAllServicesInfo: Get all service names.
    // Register instance
    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",
    	GroupName:   "group-a",
    })
    
    // Get one healthy instance (WRR)
    instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
    	ServiceName: "demo.go",
    	GroupName:   "group-a",
    	Clusters:    []string{"cluster-a"},
    })
    
    // Listen service change event
    err := namingClient.Subscribe(vo.SubscribeParam{
    	ServiceName: "demo.go",
    	GroupName:   "group-a",
    	Clusters:    []string{"cluster-a"},
    	SubscribeCallback: func (services []model.Instance, err error) {
    		log.Printf("\n\n callback return services:%s \n\n", utils.ToJsonString(services))
    	},
    })
  10. Create a Config Client (Dynamic Configuration)

    master

    Use clients.NewConfigClient to create a client for managing dynamic configurations. This is the recommended way to initialize the client using vo.NacosClientParam.

    // 1. Define ClientConfig
    clientConfig := constant.ClientConfig{
    	NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468",
    	TimeoutMs:   5000,
    }
    
    // 2. Define ServerConfigs
    serverConfigs := []constant.ServerConfig{
        {
            IpAddr: "console1.nacos.io",
            Port:   80,
        },
    }
    
    // 3. Create the Config Client
    configClient, err := clients.NewConfigClient(
        vo.NacosClientParam{
            ClientConfig:  &clientConfig,
            ServerConfigs: serverConfigs,
        },
    )
  11. Manage Dynamic Configurations

    master

    Use the configClient to manage configuration data:

    • Publish configuration: PublishConfig(vo.ConfigParam)
    • Delete configuration: DeleteConfig(vo.ConfigParam)
    • Get configuration: GetConfig(vo.ConfigParam)
    • Listen for configuration changes: ListenConfig(vo.ConfigParam) (triggers OnChange callback).
    • Cancel configuration listening: CancelListenConfig(vo.ConfigParam)
    • Search configurations: SearchConfig(vo.SearchConfigParam)
    // Publish a config
    success, err := configClient.PublishConfig(vo.ConfigParam{
        DataId:  "dataId",
        Group:   "group",
        Content: "hello world!222222",
    })
    
    // Listen for changes
    err := configClient.ListenConfig(vo.ConfigParam{
        DataId:  "dataId",
        Group:   "group",
        OnChange: func(namespace, group, dataId, data string) {
            fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
        },
    })