• Stars
    star
    1,119
  • Rank 41,306 (Top 0.9 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created about 6 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Nacos client in Golang

Nacos-sdk-go 中文

Build Status Go Report Card license


Nacos-sdk-go

Nacos-sdk-go for Go client allows you to access Nacos service,it supports service discovery and dynamic configuration.

Requirements

Supported Go version over 1.15

Supported Nacos version over 2.x

Installation

Use go get to install SDK:

$ go get -u github.com/nacos-group/nacos-sdk-go/v2

Quick Examples

  • ClientConfig
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
}
  • ServerConfig
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
}

Note:We can config multiple ServerConfig,the client will rotate request the servers

Create client

	//create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "e525eafa-f7d7-4029-83d9-008937f9d468", //we can create multiple clients with different namespaceId to support multiple namespace.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 of create clientConfig
	clientConfig := *constant.NewClientConfig(
		constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"), //When namespace is public, fill in the blank string here.
		constant.WithTimeoutMs(5000),
		constant.WithNotLoadCacheAtStart(true),
		constant.WithLogDir("/tmp/nacos/log"),
		constant.WithCacheDir("/tmp/nacos/cache"),
		constant.WithLogLevel("debug"),
	)
   // At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      "console1.nacos.io",
			ContextPath: "/nacos",
			Port:        80,
			Scheme:      "http",
		},
		{
			IpAddr:      "console2.nacos.io",
			ContextPath: "/nacos",
			Port:        80,
			Scheme:      "http",
		},
	}
	//Another way of create serverConfigs
	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")
		),
	}

	// Create naming client for service discovery
	_, _ := clients.CreateNamingClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	// Create config client for dynamic configuration
	_, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	// Another way of create naming client for service discovery (recommend)
	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)

	// Another way of create config client for dynamic configuration (recommend)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)

Create client for ACM

https://help.aliyun.com/document_detail/130146.html

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",
	}

	// a more graceful way to create config client
	client, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig: &cc,
		},
	)
   

Service Discovery

  • Register instance: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 value is DEFAULT
		GroupName:   "group-a", // default value is DEFAULT_GROUP
	})
   
  • Deregister instance:DeregisterInstance
success, err := namingClient.DeregisterInstance(vo.DeregisterInstanceParam{
		Ip:          "10.0.0.11",
		Port:        8848,
		ServiceName: "demo.go",
		Ephemeral:   true,
		Cluster:     "cluster-a", // default value is DEFAULT
		GroupName:   "group-a", // default value is DEFAULT_GROUP
	})
  • Get service:GetService
services, err := namingClient.GetService(vo.GetServiceParam{
		ServiceName: "demo.go",
		Clusters:    []string{"cluster-a"}, // default value is DEFAULT
		GroupName:   "group-a", // default value is DEFAULT_GROUP
	})
  • Get all instances:SelectAllInstances
// SelectAllInstance return all instances,include healthy=false,enable=false,weight<=0
	instances, err := namingClient.SelectAllInstances(vo.SelectAllInstancesParam{
		ServiceName: "demo.go",
		GroupName:   "group-a", // default value is DEFAULT_GROUP
		Clusters:    []string{"cluster-a"}, // default value is DEFAULT
	})
  • Get instances :SelectInstances
// SelectInstances only return the instances of healthy=${HealthyOnly},enable=true and weight>0
	instances, err := namingClient.SelectInstances(vo.SelectInstancesParam{
		ServiceName: "demo.go",
		GroupName:   "group-a", // default value is DEFAULT_GROUP
		Clusters:    []string{"cluster-a"}, // default value is DEFAULT
		HealthyOnly: true,
	})
  • Get one healthy instance(WRR):SelectOneHealthyInstance
// SelectOneHealthyInstance return one instance by WRR strategy for load balance
	// And the instance should be health=true,enable=true and weight>0
	instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
		ServiceName: "demo.go",
		GroupName:   "group-a", // default value is DEFAULT_GROUP
		Clusters:    []string{"cluster-a"}, // default value is DEFAULT
	})
  • Listen service change event:Subscribe
// Subscribe key = serviceName+groupName+cluster
	// Note: We call add multiple SubscribeCallback with the same key.
	err := namingClient.Subscribe(vo.SubscribeParam{
		ServiceName: "demo.go",
		GroupName:   "group-a", // default value is DEFAULT_GROUP
		Clusters:    []string{"cluster-a"}, // default value is DEFAULT
		SubscribeCallback: func (services []model.Instance, err error) {
			log.Printf("\n\n callback return services:%s \n\n", utils.ToJsonString(services))
		},
	})
  • Cancel listen of service change event:Unsubscribe
err := namingClient.Unsubscribe(vo.SubscribeParam{
		ServiceName: "demo.go",
		GroupName:   "group-a", // default value is DEFAULT_GROUP
		Clusters:    []string{"cluster-a"}, // default value is DEFAULT
		SubscribeCallback: func (services []model.Instance, err error) {
			log.Printf("\n\n callback return services:%s \n\n", utils.ToJsonString(services))
		},
	})
  • Get all services name:GetAllServicesInfo
serviceInfos, err := namingClient.GetAllServicesInfo(vo.GetAllServiceInfoParam{
		NameSpace: "0e83cc81-9d8c-4bb8-a28a-ff703187543f",
		PageNo:   1,
		PageSize: 10,
	}),

Dynamic configuration

  • publish config:PublishConfig
success, err := configClient.PublishConfig(vo.ConfigParam{
		DataId:  "dataId",
		Group:   "group",
		Content: "hello world!222222"})
  • delete config:DeleteConfig
success, err = configClient.DeleteConfig(vo.ConfigParam{
		DataId: "dataId",
		Group:  "group"})
  • get config info:GetConfig
content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: "dataId",
		Group:  "group"})
  • Listen config change event: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)
		},
	})
  • Cancel the listening of config change event:CancelListenConfig
err := configClient.CancelListenConfig(vo.ConfigParam{
		DataId: "dataId",
		Group:  "group",
	})
  • Search config: SearchConfig
configPage, err := configClient.SearchConfig(vo.SearchConfigParam{
		Search:   "blur",
		DataId:   "",
		Group:    "",
		PageNo:   1,
		PageSize: 10,
	})

Example

We can run example to learn how to use nacos go client.

Documentation

You can view the open-api documentation from the Nacos open-api wepsite.

You can view the full documentation from the Nacos website.

Contributing

Contributors are welcomed to join Nacos-sdk-go project. Please check CONTRIBUTING.md about how to contribute to this project.

Contact

  • Join us from DingDing Group(23191211).
  • Gitter: Nacos's IM tool for community messaging, collaboration and discovery.
  • Twitter: Follow along for latest nacos news on Twitter.
  • Weibo: Follow along for latest nacos news on Weibo (Twitter of China version).
  • Nacos SegmentFault: Get the latest notice and prompt help from SegmentFault.
  • Email Group:

More Repositories

1

nacos-docker

This project contains a Docker image meant to facilitate the deployment of Nacos .
Shell
1,405
star
2

nacos-examples

Nacos Examples
Java
953
star
3

r-nacos

Nacos server re-implemented in Rust.
Rust
812
star
4

nacos-spring-boot-project

Nacos ECO Project for Spring Boot
Java
785
star
5

nacos-spring-project

Nacos ECO Project for Spring Framework
Java
755
star
6

nacos-k8s

This project contains a Nacos Docker image meant to facilitate the deployment of Nacos on Kubernetes using StatefulSets.
Go
595
star
7

nacos-sdk-csharp

This nacos csharp sdk
C#
420
star
8

nacos-sdk-python

nacos python sdk
Python
362
star
9

nacos-sync

Service Sync component
Java
292
star
10

nacos-sdk-nodejs

nacos node.js sdk client
TypeScript
291
star
11

nacos-sdk-cpp

C++ client for Nacos
C++
125
star
12

nacos-sdk-rust

nacos client for rust
Rust
117
star
13

grpc-java-registry-nacos

gRPC Nacos registry integration
Java
97
star
14

nacos-group.github.io

nacos-group.github.io
MDX
97
star
15

nacos-plugin

A collection of Nacos plug-ins, providing Nacos with pluggable plug-in capabilities, support for user customization and high scalability
Java
91
star
16

nacos-coredns-plugin

Nacos DNS-F Client Based On CoreDNS
Go
83
star
17

nacos-template

nacos-template include PPT template and knote
70
star
18

nginx-nacos-upstream

nginx nacos module. subscribe service and configuration from nacos instead of modifying and reloading nginx.conf
C
61
star
19

nacos-confd

Go
40
star
20

nacos-istio

Nacos integrate with Istio as a MCP server
Go
38
star
21

nacos-controller

nacos k8s controller
Go
25
star
22

dubbo-registry-nacos

Dubbo Registry support for Nacos
14
star
23

nacos-k8s-sync

A component for sync services between Nacos and Kubernetes.
Go
12
star
24

nacos-sdk-lua

Lua
12
star
25

nacos-activity

The documents presented in nacos activities
11
star
26

nacos-sdk-php

PHP
11
star
27

nacos-ctl

The controller command sdk for nacos
Java
7
star
28

logback-adapter

Java
5
star
29

acm2nacos-spring-cloud-example

Java
4
star
30

nacos-tutorial

Nacos 知行实验仓库
2
star
31

acm2nacos-java-example

Java
2
star
32

apollo-2-nacos-migration

Apollo迁移到Nacos的脚本工程
Java
1
star
33

nacos-logo

The logo files for nacos
1
star