Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop endpoint #673

Merged
merged 2 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions clients/client_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ func setConfig(param vo.NacosClientParam) (iClient nacos_client.INacosClient, er
_ = client.SetServerConfig(nil)
} else {
for i := range param.ServerConfigs {
if param.ServerConfigs[i].Port == 0 {
param.ServerConfigs[i].Port = 8848
}
if param.ServerConfigs[i].GrpcPort == 0 {
param.ServerConfigs[i].GrpcPort = param.ServerConfigs[i].Port + constant.RpcPortOffset
}
Expand Down
21 changes: 21 additions & 0 deletions common/constant/client_config_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,27 @@ func WithEndpoint(endpoint string) ClientOption {
}
}

// WithEndpointContextPath ...
func WithEndpointContextPath(endpointContextPath string) ClientOption {
return func(config *ClientConfig) {
config.EndpointContextPath = endpointContextPath
}
}

// WithEndpointQueryParams ...
func WithEndpointQueryParams(endpointQueryPrams string) ClientOption {
return func(config *ClientConfig) {
config.EndpointQueryParams = endpointQueryPrams
}
}

// WithClusterName ...
func WithClusterName(clusterName string) ClientOption {
return func(config *ClientConfig) {
config.ClusterName = clusterName
}
}

// WithRegionId ...
func WithRegionId(regionId string) ClientOption {
return func(config *ClientConfig) {
Expand Down
3 changes: 3 additions & 0 deletions common/constant/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ type ClientConfig struct {
LogRollingConfig *ClientLogRollingConfig // log rolling config
TLSCfg TLSConfig // tls Config
AsyncUpdateService bool // open async update service by query
EndpointContextPath string // the address server endpoint contextPath
EndpointQueryParams string // the address server endpoint query params
ClusterName string // the address server clusterName
}

type ClientLogSamplingConfig struct {
Expand Down
5 changes: 4 additions & 1 deletion common/http_agent/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@ import (
)

func get(client *http.Client, path string, header http.Header, timeoutMs uint64, params map[string]string) (response *http.Response, err error) {
if !strings.HasSuffix(path, "?") {
if !strings.Contains(path, "?") {
path = path + "?"
}

for key, value := range params {
if !strings.HasSuffix(path, "&") {
path = path + "&"
}
path = path + key + "=" + value + "&"
}
if strings.HasSuffix(path, "&") {
Expand Down
42 changes: 33 additions & 9 deletions common/nacos_server/nacos_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ type NacosServer struct {
lastSrvRefTime int64
vipSrvRefInterMills int64
contextPath string
endpointContextPath string
endpointQueryParams string
clusterName string
currentIndex int32
ServerSrcChangeSignal chan struct{}
}
Expand All @@ -75,14 +78,18 @@ func NewNacosServer(ctx context.Context, serverList []constant.ServerConfig, cli
timeoutMs: timeoutMs,
endpoint: endpoint,
vipSrvRefInterMills: 10000,
endpointContextPath: clientCfg.EndpointContextPath,
endpointQueryParams: clientCfg.EndpointQueryParams,
clusterName: clientCfg.ClusterName,
contextPath: clientCfg.ContextPath,
ServerSrcChangeSignal: make(chan struct{}, 1),
}
if severLen > 0 {
ns.currentIndex = rand.Int31n(int32(severLen))
} else {
ns.initRefreshSrvIfNeed(ctx)
}

ns.initRefreshSrvIfNeed(ctx)
_, err := securityLogin.Login()

if err != nil {
Expand Down Expand Up @@ -264,31 +271,44 @@ func (server *NacosServer) initRefreshSrvIfNeed(ctx context.Context) {
if server.endpoint == "" {
return
}
server.refreshServerSrvIfNeed()

if len(strings.TrimSpace(server.endpointContextPath)) == 0 {
server.endpointContextPath = "nacos"
}

if len(strings.TrimSpace(server.clusterName)) == 0 {
server.clusterName = "serverlist"
}
urlString := "http://" + server.endpoint + "/" + strings.TrimSpace(server.endpointContextPath) + "/" + strings.TrimSpace(server.clusterName)
if len(strings.TrimSpace(server.endpointQueryParams)) != 0 {
urlString += "?" + server.endpointQueryParams
}
logger.Infof("nacos address server url: <%s>", urlString)

server.refreshServerSrvIfNeed(urlString)
go func() {
for {
select {
case <-ctx.Done():
return
default:
time.Sleep(time.Duration(1) * time.Second)
server.refreshServerSrvIfNeed()
time.Sleep(time.Duration(10) * time.Second)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里建议用个case timer做这个事情
default不要了

server.refreshServerSrvIfNeed(urlString)
}
}
}()

}

func (server *NacosServer) refreshServerSrvIfNeed() {
func (server *NacosServer) refreshServerSrvIfNeed(urlString string) {
if util.CurrentMillis()-server.lastSrvRefTime < server.vipSrvRefInterMills && len(server.serverList) > 0 {
return
}

var list []string
urlString := "http://" + server.endpoint + "/nacos/serverlist"

result := server.httpAgent.RequestOnlyResult(http.MethodGet, urlString, nil, server.timeoutMs, nil)
list = strings.Split(result, "\n")
logger.Infof("http nacos server list: <%s>", result)

var servers []constant.ServerConfig
contextPath := server.contextPath
Expand All @@ -314,9 +334,13 @@ func (server *NacosServer) refreshServerSrvIfNeed() {
if len(servers) > 0 {
if !reflect.DeepEqual(server.serverList, servers) {
server.Lock()
logger.Infof("server list is updated, old: <%v>,new:<%v>", server.serverList, servers)
var serverPrev = server.serverList
logger.Infof("server list is updated, old: <%v>,new:<%v>", serverPrev, servers)

server.serverList = servers
server.ServerSrcChangeSignal <- struct{}{}
if serverPrev != nil {
server.ServerSrcChangeSignal <- struct{}{}
}
server.lastSrvRefTime = util.CurrentMillis()
server.Unlock()
}
Expand Down
145 changes: 145 additions & 0 deletions example/config-endpoint/main-endpoint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* 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
*
* http://www.apache.org/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 main

import (
"fmt"
"time"

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

func main() {
//create ClientConfig
cc := *constant.NewClientConfig(
constant.WithNamespaceId(""),
constant.WithTimeoutMs(5000),
constant.WithNotLoadCacheAtStart(true),
constant.WithLogDir("/tmp/nacos/log"),
constant.WithCacheDir("/tmp/nacos/cache"),
constant.WithLogLevel("debug"),
constant.WithAppName("yiyantest"),
constant.WithEndpoint("jmenv.tbsite.net:8080"),
constant.WithClusterName("serverlist"),
constant.WithEndpointQueryParams("nofix=1"),
constant.WithEndpointContextPath("nacos"),
)

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

if err != nil {
panic(err)
}

//publish config
//config key=dataId+group+namespaceId
_, err = client.PublishConfig(vo.ConfigParam{
DataId: "test-data",
Group: "test-group",
Content: "hello world!",
})
_, err = client.PublishConfig(vo.ConfigParam{
DataId: "test-data-2",
Group: "test-group",
Content: "hello world!",
})
if err != nil {
fmt.Printf("PublishConfig err:%+v \n", err)
}
time.Sleep(1 * time.Second)
//get config
content, err := client.GetConfig(vo.ConfigParam{
DataId: "test-data",
Group: "test-group",
})
fmt.Println("GetConfig,config :" + content)

//Listen config change,key=dataId+group+namespaceId.
err = client.ListenConfig(vo.ConfigParam{
DataId: "test-data",
Group: "test-group",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("config changed group:" + group + ", dataId:" + dataId + ", content:" + data)
},
})

err = client.ListenConfig(vo.ConfigParam{
DataId: "test-data-2",
Group: "test-group",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("config changed group:" + group + ", dataId:" + dataId + ", content:" + data)
},
})

time.Sleep(1 * time.Second)
var content2 = "helo 130"
_, err = client.PublishConfig(vo.ConfigParam{
DataId: "test-data",
Group: "test-group",
Content: content2,
})
if err == nil {
fmt.Println("publish config success:" + "test-group" + ", dataId:" + "test-data" + ", content:" + content2)

} else {
fmt.Println("publish config fail :" + "test-group" + ", dataId:" + "test-data" + ", content:" + content2)

}
time.Sleep(1 * time.Second)

_, err = client.PublishConfig(vo.ConfigParam{
DataId: "test-data-2",
Group: "test-group",
Content: "test-listen",
})

time.Sleep(2 * time.Second)

time.Sleep(1 * time.Second)
_, err = client.DeleteConfig(vo.ConfigParam{
DataId: "test-data",
Group: "test-group",
})
fmt.Println("delete config success:" + "test-group" + ", dataId:" + "test-data")

time.Sleep(1 * time.Second)

/* //cancel config change
err = client.CancelListenConfig(vo.ConfigParam{
DataId: "test-data",
Group: "test-group",
})
*/
searchPage, _ := client.SearchConfig(vo.SearchConfigParam{
Search: "blur",
DataId: "test-data",
Group: "",
PageNo: 1,
PageSize: 10,
})
fmt.Printf("Search config:%+v \n", searchPage)

time.Sleep(1000 * time.Second)

}
Loading