nacos-sdk-go

module
v0.0.0-...-d14e12a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2020 License: Apache-2.0

README

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.12

Supported Nacos version over 1.x

Installation

Use go get to install SDK:

$ go get -u github.com/lei006/nacos-sdk-go

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 get Nacos server addresses
	RegionId             string // the regionId for kms
	AccessKey            string // the AccessKey for kms
	SecretKey            string // the SecretKey for kms
	OpenKMS              bool   // it's to open kms,default is false. https://help.aliyun.com/product/28933.html
	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{
	ContextPath string // the nacos server context path
	IpAddr      string // the nacos server address
	Port        uint64 // the nacos server port
}

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

Create client
clientConfig := constant.ClientConfig{
	NamespaceId:         "e525eafa-f7d7-4029-83d9-008937f9d468", //we can create multiple clients with different namespaceId to support multiple namespace
	TimeoutMs:           5000,
	NotLoadCacheAtStart: true,
	LogDir:              "/tmp/nacos/log",
	CacheDir:            "/tmp/nacos/cache",
	RotateTime:          "1h",
	MaxAge:              3,
	LogLevel:            "debug",
} 

// At least one ServerConfig 
serverConfigs := []constant.ServerConfig{
    {
        IpAddr:      "console1.nacos.io",
        ContextPath: "/nacos",
        Port:        80,
    },
    {
    	IpAddr:      "console2.nacos.io",
    	ContextPath: "/nacos",
    	Port:        80,
    },
}

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

// Create config client for dynamic configuration
configClient, err := clients.CreateConfigClient(map[string]interface{}{
	"serverConfigs": serverConfigs,
	"clientConfig":  clientConfig,
})
    
Service Discovery
  • Register instance:RegisterInstance

success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
    Ip:          "192.168.1.110",
    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:          "192.168.1.110",
    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.SubscribeService, 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.SubscribeService, err error) {
        log.Printf("\n\n callback return services:%s \n\n", utils.ToJsonString(services))
    },
})

  • Get all services name:GetAllServicesInfo

serviceInfos, err := client.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

Directories

Path Synopsis
naming_client
* Copyright 1999-2020 Alibaba Group Holding Ltd.
* Copyright 1999-2020 Alibaba Group Holding Ltd.
common
http_agent
* Copyright 1999-2020 Alibaba Group Holding Ltd.
* Copyright 1999-2020 Alibaba Group Holding Ltd.
example
inner
uuid
Package uuid provides implementation of Universally Unique Identifier (UUID).
Package uuid provides implementation of Universally Unique Identifier (UUID).
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL