Giter Site home page Giter Site logo

nacos-sdk-go's Introduction

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:

nacos-sdk-go's People

Contributors

atlanssia avatar binbin0325 avatar brotherlu-xcq avatar caorong avatar chuntaojun avatar dependabot[bot] avatar habby-chen avatar haifeiwu avatar horizonzy avatar howie59 avatar komachision avatar legenove avatar li-jin-gou avatar liguozhong avatar lixiangwuxian avatar lzp0412 avatar mark4z avatar penglq avatar realjacksun avatar robynron avatar shenqidebaozi avatar shiyiyue1102 avatar sivyer9303 avatar specialyang avatar stulzq avatar tonglin96 avatar undom avatar x-lambda avatar xushuhui avatar zensh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nacos-sdk-go's Issues

一些建议

  1. 代码不太符合标准go的代码格式,好多感觉是java的风格, 少用interface{}断言。
  2. 很多地方,go都习惯于用*Object, 而不是直接使用实体。
  3. 配置创建使用 NewObject(...options ClientOption) 这种模式更通用
    https://github.com/grpc/grpc-go/blob/master/server.go 请参考 NewServer部分

然后grpc的支持是否直接集成进来,我要跨语言支持,java那部分grpchttps://github.com/nacos-group/grpc-java-registry-nacos我看已经有实现了。我希望这一部分,官方能协调,保证服务定义路径啥的一致,这样便于跨语言服务的gRPC使用。感谢。

以上这些,有需要,我可以协助修改。

nacos-sdk-go问题收集

此issue的目的

  • 收集用户使用nacos-sdk-go过程遇到的问题
  • 收集用户对nacos-sdk-go的建议,包括功能、代码架构等

我们将根据您反馈,规划nacos-sdk-go的开发计划,一起解决目前存在的问题,完善nacos-sdk-go。

再次感谢您的参与!!!

abstract log interface

What would you like to be added:
Give an abstract log interface, and a default log implementation which support log level,log rotate and log format。
Why is this needed:
Users may want to implement their own log libraries,so we need give an interface.

UUID兼容性问题

satori/go.uuid新版和旧版接口不同,建议换一个UUID库:

nacos_server\nacos_server.go:102:44: multiple-value uuid .NewV4() in single-value context

Getting the deleted configuration is still readable

I think this is a design flaw that does not set whether to read cached data or specify the source of the returned data

	content, err := client.GetConfig(vo.ConfigParam{
		DataId: "com.hello",
		Group:  "marx"})

	fmt.Println(content, err)

out:
2019/07/02 11:26:04 [INFO] logDir:<data/nacos/log> cacheDir:</private/var/folders/w4/d_d_m03523j12lnn4ypdq90m0000gp/T/cache>
hello world2

Nacos 为什么注册服务老是失败?

代码

`type NacosClient struct {
Client config_client.IConfigClient
NamingClient naming_client.INamingClient
}

// New Nacos Client
func NewNacos(option *Options) *NacosClient {
clientConfig := constant.ClientConfig{
TimeoutMs: option.TimeoutMs,
ListenInterval: option.ListenInterval,
BeatInterval: option.BeatInterval,
}
serverConfigs := []constant.ServerConfig{
constant.ServerConfig{
ContextPath: "/nacos",
IpAddr: option.Address,
Port: option.Port,
},
}
// Create Config Center
client, err := clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": serverConfigs,
"clientConfig": clientConfig,
})
if err != nil {
panic(err)
}
// Create Register Center
namingClient,err:=clients.CreateNamingClient(map[string]interface{}{
"serverConfigs":serverConfigs,
"clientConfig":clientConfig,
})
if err!=nil{
panic(err)
}
return &NacosClient{Client: client,NamingClient: namingClient}
}
`

注册服务

`// Register Service
func (c *NacosClient) Register(ip string,port uint64) bool {
ok,err:=c.NamingClient.RegisterInstance(vo.RegisterInstanceParam{
Ip: ip,
Port: port,
ServiceName: "demo.go",
Weight: 10,
ClusterName: "a",
Enable: true,
Healthy: true,
Ephemeral: true,
})
if err!=nil{
return false
}
return ok
}

// Deregister Service
func (c *NacosClient) Deregister(ip string,port uint64) bool {
ok ,err:=c.NamingClient.DeregisterInstance(vo.DeregisterInstanceParam{
Ip: ip,
Port: port,
ServiceName: "demo.go",
Cluster: "a",
Ephemeral: true,
})
if err!=nil{
return false
}
return ok
}`

Nacos api configs interface tenant parameter problem

The tenant in the project's instructions should be the id corresponding to the namespace, not the namespace name.

Current nacos version 1.1.3

  1. request
 /nacos/v1/cs/configs?dataId={dataId}&group={group}&tenant=public
  1. ruturn message
config data not exist

image

image


The corresponding location in the above image should pass in the parameter id of the namespace, not the namespace name. The comments in the code can be misleading.

host_reator GetServiceInfo 并发情况下出错

服务启动时,并发获取实例。出现异常 Service Hosts instance list is empty!
经过分析在host_reator/GetServiceInfo func中 高并发下对Map操作的逻辑有问题。

  func (hr *HostReactor) GetServiceInfo(serviceName string, clusters string) model.Service {
	key := utils.GetServiceCacheKey(serviceName, clusters)
	cacheService, ok := hr.serviceInfoMap.Get(key)
 	if !ok {
 		cacheService = model.Service{Name: serviceName, Clusters: clusters}
 		hr.serviceInfoMap.Set(key, cacheService)
 		hr.updateServiceNow(serviceName, clusters)
 	}
 	newService, _ := hr.serviceInfoMap.Get(key)
 
 	return newService.(model.Service)
 }

Give some example

What would you like to be added:
We need to give some example to guide new users
Why is this needed:

readme文档中的错误

1.注册服务实例:RegisterInstance 中缺失MetaData导致 nacos服务中空指针异常,
异常为:Can not get hosts from nacos server. serviceId: **

image

image

在用例代码中应该加入MetaData属性

2.注销服务实例:DeregisterInstance 传入的参数错误,应该为DeregisterInstanceParam
image

Who is using nacos-sdk-go

此 Issue 的目的

  • 收集在生产上使用nacos-sdk-go的用户

  • 聆听社区内一线开发和运维人员的声音,完善nacos-sdk-go

  • 吸引更多的人参与社区贡献

我们期待您能提供

  • 您所在公司、学校或组织
  • 您所在的城市、国家
  • 您的联系方式:微博、邮箱、微信 (至少一个)
  • 您将nacos-sdk-go用于哪些业务场景,需要哪些功能特性

登记使用情况的好处

  • 专家服务(半天内响应,优先支持,落地方案和场景讨论),帮助大家更高效的落地Nacos
  • 企业技术影响力构建(如虎牙Nacos落地最佳实践,帮虎牙赢得技术影响力),我们可以协助企业输出这样的内容和宣传,以便形成丰富的Nacos案例库,方便了解彼此公司使用情况。
  • 个人影响力构建,Committer候选人 (登记用户可以获得1:1 Nacos committer培养的支持)

您可以参考以下格式

  • 组织:阿里巴巴
  • 地点:**杭州
  • 联系方式:[email protected]
  • 场景:服务发现和配置管理
  • 服务框架:SpringCloud / Dubbo / gRPC / K8S / ...
  • 使用规模:100个配置 + 100个服务

如果您在开发和生产上线中遇到什么问题,可搜索钉钉群23191211加入,我们会及时跟进您反馈的问题和使用情况。

Access to ci/cd tools

What would you like to be added:
we need to access to ci/cd tools like travis to ensure code quality
Why is this needed:

selectOneHealthyInstances 性能问题

naming_client/selectOneHealthyInstances/random func 性能问题,经过使用通过pprof分析出来 由于random func 频繁扩容slice 导致 消耗cpu 资源严重。后续我将推送代码 修复这个问题。
image

部分地区首次监听无效

使用中发现部分地区首次启动的时候,ListenConfig不能生效,无法首次拉取到远端配置,导致远端更新的时候也无法同步更新。

	configClient.ListenConfig(vo.ConfigParam{
		DataId: "xxx.json",
		Group:  "DEFAULT_GROUP",
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})

然后在ListenConfig之前加了GetConfig就可以了,感觉是个bug,麻烦定位看下

        configClient.GetConfig(vo.ConfigParam{
		DataId: "xxx.json",
		Group:  "DEFAULT_GROUP",})

	configClient.ListenConfig(vo.ConfigParam{
		DataId: "xxx.json",
		Group:  "DEFAULT_GROUP",
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})

clients/client_factory.go 中 CreateNamingClient 参数的配置项可否换成引用类型?

在 setConfig 函数体中对配置实例对断言验证都是类型 constant.ClientConfig, 可否换成 *constant.ClientConfig?CI中过不了 gocritic 的 hugeParam lint。

func setConfig(properties map[string]interface{}) (iClient nacos_client.INacosClient, err error) {
	client := nacos_client.NacosClient{}
	if clientConfigTmp, exist := properties[constant.KEY_CLIENT_CONFIG]; exist {
		if clientConfig, ok := clientConfigTmp.(constant.ClientConfig); ok {
			err = client.SetClientConfig(clientConfig)
			if err != nil {
				return
			}
		}
	} else {
		_ = client.SetClientConfig(constant.ClientConfig{
			TimeoutMs:      10 * 1000,
			ListenInterval: 30 * 1000,
			BeatInterval:   5 * 1000,
		})
	}
	// 设置 serverConfig
	if serverConfigTmp, exist := properties[constant.KEY_SERVER_CONFIGS]; exist {
		if serverConfigs, ok := serverConfigTmp.([]constant.ServerConfig); ok {
			err = client.SetServerConfig(serverConfigs)
			if err != nil {
				return
			}
		}
	} else {
		clientConfig, _ := client.GetClientConfig()
		if len(clientConfig.Endpoint) <= 0 {
			err = errors.New("server configs not found in properties")
			return
		}
		client.SetServerConfig([]constant.ServerConfig{})
	}

	iClient = &client

	return
}

After the configuration is removed, Listen continually returns the previous value

It might have something to do with this(https://github.com/nacos-group/nacos-sdk-go/issues/9)

https://nacos.io/en-us/docs/open-api.html
Listen for configurations
Description
This API is used to listen for configurations in Nacos to capture configuration changes. In case of any configuration changes, you can use the Get Configurations API to obtain the latest value of the configuration and dynamically refresh the local cache.

A listener is registered using an asynchronous servlet. The nature of registering a listener is to compare the configuration value and the MD5 value of it with that of the backend. If the values differ, the inconsistent configuration is returned immediately. Otherwise, an empty string is returned after 30 seconds.
success, _ := client.PublishConfig(vo.ConfigParam{
		DataId:  "com.hello",
		Group:   "marx",
		Content: "hello world",
	})
	fmt.Println("Publish Content: ", "hello world, result", success)
	time.Sleep(10 * time.Second)

	success, _ = client.PublishConfig(vo.ConfigParam{
		DataId:  "com.hello",
		Group:   "marx",
		Content: "hello ma",
	})
	fmt.Println("Publish Content: ", "hello ma, result", success)
	time.Sleep(10 * time.Second)

	success, _ = client.PublishConfig(vo.ConfigParam{
		DataId:  "com.hello",
		Group:   "marx",
		Content: "hello max",
	})
	fmt.Println("Publish Content: ", "hello marx, result", success)
	time.Sleep(10 * time.Second)

	success, _ = client.DeleteConfig(vo.ConfigParam{
		DataId: "com.hello",
		Group:  "marx",
	})
	fmt.Println("Delete Content: ", "hello marx, result", success)

	time.Sleep(2 * time.Minute)

out:
2019/07/02 14:44:03 [INFO] logDir:<data/nacos/log> cacheDir:</private/var/folders/w4/d_d_m03523j12lnn4ypdq90m0000gp/T/cache>
Publish Content: hello world, result true
group:marx, dataId:com.hello, data:hello world
Publish Content: hello ma, result true
group:marx, dataId:com.hello, data:hello ma
Publish Content: hello marx, result true
group:marx, dataId:com.hello, data:hello max
Delete Content: hello marx, result true
group:marx, dataId:com.hello, data:hello max
group:marx, dataId:com.hello, data:hello max
group:marx, dataId:com.hello, data:hello max
group:marx, dataId:com.hello, data:hello max
... ...
group:marx, dataId:com.hello, data:hello max
... ...

Code Copied Without Preservation of Copyright and License Notices

Hi guys,

It looks like the code for your concurrent map here is a direct copy/paste of our implementation (including stuff that we commented out and everything).

Do feel free to use the code (it's MIT-licensed) and I hope you find it useful, but it would be great if you could follow the license requirement, requiring preservation of copyright and license notices.

Thanks

configClient.GetConfig return nothing

please help!!!
configClient.GetConfig return nothing

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
)

func main() {
	clientConfig := constant.ClientConfig{
		TimeoutMs:      10 * 1000,
		ListenInterval: 10 * 1000,
		BeatInterval:   5 * 1000,
		NamespaceId:    "test",
		// LogDir:         "/nacos/logs",
		// CacheDir:       "/nacos/cache",
		NotLoadCacheAtStart: true, //在启动时不读取本地缓存数据,true--不读取,false--读取
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      "localhost",
			ContextPath: "/nacos",
			Port:        8848,
		},
	}
	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		log.Fatal(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: "test.yml",
		Group:  "testGroup",
	})
	if err != nil {
		log.Fatal(err)
	}
	if content == "" {
		log.Printf("getConfig: nil")
	}
	log.Printf("getConfig: %v:", content) // <=============== not output

	err = configClient.ListenConfig(vo.ConfigParam{ // <=========== output in OnChange is normal
		DataId: "test.yml",
		Group:  "testGroup",

		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("namespace:" + namespace + ", group:" + group + ", dataId:" + dataId + ", data:" + data)
			serverViper := viper.New()
			serverViper.SetConfigType("yaml")
			serverViper.ReadConfig(strings.NewReader(data))

			fmt.Println("aaa", serverViper.Get("aaa"))

		},
	})
	if err != nil {
		log.Fatal(err)

	}
	// router := gin.Default()
	// router.Run()
	select {}
}

output:

2020/07/31 14:24:00 [INFO] logDir:</Users/gattaca/git/mygo/go-server/log>   cacheDir:</Users/gattaca/git/mygo/go-server/cache>
namespace:test, group:testGroup, dataId:test.yml, data:aaa: 10
aaa 10

module github.com/xxx/go-server

go 1.14

require (
	github.com/gin-gonic/gin v1.6.3
	github.com/go-playground/validator/v10 v10.3.0 // indirect
	github.com/golang/protobuf v1.4.2
	github.com/json-iterator/go v1.1.10 // indirect
	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
	github.com/modern-go/reflect2 v1.0.1 // indirect
	github.com/nacos-group/nacos-sdk-go v0.4.0
	github.com/spf13/viper v1.7.0
	golang.org/x/net v0.0.0-20200707034311-ab3426394381 // indirect
	golang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1 // indirect
	google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f // indirect
	google.golang.org/grpc v1.30.0
	google.golang.org/protobuf v1.25.0
	gopkg.in/yaml.v2 v2.3.0 // indirect
)

Listen mutiple config in a connection

What would you like to be added:
When we call ListenConfig(param vo.ConfigParam), put the listen task to cache, and other gorutine to get the tasks for listening change.
Why is this needed:
Now we only listen one config in a connect. This will cause waste of client resources and increase the nacos server load.

The NamespaceId is configured incorrectly, but the operation can also succeed

There seems to be no filter limit

         "clientConfig": constant.ClientConfig{
			//NamespaceId:          "bf8ab528-e832-4ebc-ab94-dd7ec7c0e843", -- right
			NamespaceId:          "marx", // wrong
			...
		},

         success, err := client.PublishConfig(vo.ConfigParam{
		DataId:  "com.hello",
		Group:   "marx",
		Content: "hello world2",
	})
	
	fmt.Println(success, err)

	content, err := client.GetConfig(vo.ConfigParam{
		DataId: "com.hello",
		Group:  "marx"})

	fmt.Println(content, err)

out:
2019/07/02 11:41:54 [INFO] logDir:<data/nacos/log> cacheDir:</private/var/folders/w4/d_d_m03523j12lnn4ypdq90m0000gp/T/cache>
true
hello world2

Listen mutiple config in a connection

What would you like to be added:
When we call ListenConfig(param vo.ConfigParam), put the listen task to cache, and other gorutine to get the tasks for listening change.
Why is this needed:
Now we only listen one config in a connect. This will cause waste of client resources and increase the nacos server load.

nacos configClient使用监听方法监听无效

我使用的方法如下
err = configClient.ListenConfig(vo.ConfigParam{ DataId: dataId, Group: group, Content: content, OnChange: func(namespace, group, dataId, data string) { fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data) }, })
这个方法中的各项配置都是正确的,且可以使用getConfig下载,然后我使用
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
来保证该程序不会退出,最后看日志中的内容如下:
2020/04/16 17:43:25 [client.ListenConfig] request url: http://xxxxx/nacos/v1/cs/configs/listener ;params: map[Listening-Configs:yar�DEV�1088958d4d6bcf1947632b196ef07a54�f3004c58-3522-4e65-8a0a-5043721a51a6�] ;header: map[Content-Type:[application/x-www-form-urlencoded] Long-Pulling-Timeout:[30000]] 2020/04/16 17:43:25 [client.ListenConfig] no change
而实际上我的配置已经通过web控制台进行了修改。
本人是在windows环境下进行的测试,不知道环境是否对该问题有影响

User document update

What would you like to be added:
We need to update our user document and give an english document;
Why is this needed:

GetAllServicesInfo fail

GetAllServicesInfo interface changes. /getAll -> /service/list.

I would like to try my hand at the job.

注册的服务无法查询

example/service/main.go 修改serverconfig和时间后 注册的服务在Nacos都无法看到是为什么?

基于README示例进行订阅后,Nacos面板的“订阅者列表”中却没有记录显示

Nacos版本1.1.4

namingClient初始化配置:

r, err := NewNacosRegistry(constant.ClientConfig{
	TimeoutMs:            10 * 1000,
	ListenInterval:       30 * 1000,
	NamespaceId:          "d70053b1-7daa-438a-ab03-4835fc57b747", //nacos命名空间
	UpdateThreadNum:      20, 
	NotLoadCacheAtStart:  true,
	UpdateCacheWhenEmpty: true,
}, []constant.ServerConfig{
	{
		IpAddr:      "172.16.13.95",
		ContextPath: "/nacos",
		Port:        8848,
	},
})

订阅代码:

func (r *NacosRegistry) Subscribe(
	info yunfan.ServiceInfo, callback yunfan.RegistryChangeFunc) error {
	r.subscribeParam = &vo.SubscribeParam{
		ServiceName: info.Name,
		Clusters:    []string{info.Cluster},
		SubscribeCallback: func(services []model.SubscribeService, err error) {
			log.Infof("\n\n callback return services:%s \n\n",
				utils.ToJsonString(services))
			callback()
		},
	}
	return r.client.Subscribe(r.subscribeParam)
}

实际订阅应该是成功的,因为后续有服务注册的时候 callback 可以成功打印变动,但是Nacos面板中就是不能显示出对应记录,换过几个命名空间都一样。

remove uuid package dependencies

What would you like to be added:
remove github.com/satori/go.uuid dependencies,copy the dependent package to ourself project
Why is this needed:
this package is not compatible with v1.2.0 and v1.1.0. When other project import Nacos-sdk-go may cause conflict on github.com/satori/go.uuid.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.