dubbo.apache.org/dubbo-go/v3@v3.1.1/remoting/nacos/builder.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package nacos
    19  
    20  import (
    21  	"net"
    22  	"strconv"
    23  	"strings"
    24  	"time"
    25  )
    26  
    27  import (
    28  	nacosClient "github.com/dubbogo/gost/database/kv/nacos"
    29  	"github.com/dubbogo/gost/log/logger"
    30  
    31  	nacosConstant "github.com/nacos-group/nacos-sdk-go/v2/common/constant"
    32  
    33  	perrors "github.com/pkg/errors"
    34  )
    35  
    36  import (
    37  	"dubbo.apache.org/dubbo-go/v3/common"
    38  	"dubbo.apache.org/dubbo-go/v3/common/constant"
    39  	"dubbo.apache.org/dubbo-go/v3/config"
    40  )
    41  
    42  // NewNacosConfigClientByUrl read the config from url and build an instance
    43  func NewNacosConfigClientByUrl(url *common.URL) (*nacosClient.NacosConfigClient, error) {
    44  	sc, cc, err := GetNacosConfig(url)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	clientName := url.GetParam(constant.ClientNameKey, "")
    49  	if len(clientName) <= 0 {
    50  		return nil, perrors.New("nacos client name must set")
    51  	}
    52  	return nacosClient.NewNacosConfigClient(clientName, true, sc, cc)
    53  }
    54  
    55  // GetNacosConfig will return the nacos config
    56  func GetNacosConfig(url *common.URL) ([]nacosConstant.ServerConfig, nacosConstant.ClientConfig, error) {
    57  	if url == nil {
    58  		return []nacosConstant.ServerConfig{}, nacosConstant.ClientConfig{}, perrors.New("url is empty!")
    59  	}
    60  
    61  	if len(url.Location) == 0 {
    62  		return []nacosConstant.ServerConfig{}, nacosConstant.ClientConfig{},
    63  			perrors.New("url.location is empty!")
    64  	}
    65  
    66  	addresses := strings.Split(url.Location, ",")
    67  	serverConfigs := make([]nacosConstant.ServerConfig, 0, len(addresses))
    68  	for _, addr := range addresses {
    69  		ip, portStr, err := net.SplitHostPort(addr)
    70  		if err != nil {
    71  			return []nacosConstant.ServerConfig{}, nacosConstant.ClientConfig{},
    72  				perrors.WithMessagef(err, "split [%s] ", addr)
    73  		}
    74  		portContextPath := strings.Split(portStr, constant.PathSeparator)
    75  		port, err := strconv.Atoi(portContextPath[0])
    76  		if err != nil {
    77  			return []nacosConstant.ServerConfig{}, nacosConstant.ClientConfig{},
    78  				perrors.WithMessagef(err, "port [%s] ", portContextPath[0])
    79  		}
    80  		var contextPath string
    81  		if len(portContextPath) > 1 {
    82  			contextPath = constant.PathSeparator + strings.Join(portContextPath[1:], constant.PathSeparator)
    83  		}
    84  		serverConfigs = append(serverConfigs, nacosConstant.ServerConfig{IpAddr: ip, Port: uint64(port), ContextPath: contextPath})
    85  	}
    86  
    87  	timeout := url.GetParamDuration(constant.NacosTimeout, constant.DefaultRegTimeout)
    88  
    89  	clientConfig := nacosConstant.ClientConfig{
    90  		TimeoutMs:            uint64(int32(timeout / time.Millisecond)),
    91  		NamespaceId:          url.GetParam(constant.NacosNamespaceID, ""),
    92  		Username:             url.GetParam(constant.NacosUsername, ""),
    93  		Password:             url.GetParam(constant.NacosPassword, ""),
    94  		BeatInterval:         url.GetParamInt(constant.NacosBeatIntervalKey, 5000),
    95  		AppName:              url.GetParam(constant.NacosAppNameKey, ""),
    96  		Endpoint:             url.GetParam(constant.NacosEndpoint, ""),
    97  		RegionId:             url.GetParam(constant.NacosRegionIDKey, ""),
    98  		AccessKey:            url.GetParam(constant.NacosAccessKey, ""),
    99  		SecretKey:            url.GetParam(constant.NacosSecretKey, ""),
   100  		OpenKMS:              url.GetParamBool(constant.NacosOpenKmsKey, false),
   101  		CacheDir:             url.GetParam(constant.NacosCacheDirKey, ""),
   102  		UpdateThreadNum:      url.GetParamByIntValue(constant.NacosUpdateThreadNumKey, 20),
   103  		NotLoadCacheAtStart:  url.GetParamBool(constant.NacosNotLoadLocalCache, true),
   104  		LogDir:               url.GetParam(constant.NacosLogDirKey, ""),
   105  		LogLevel:             url.GetParam(constant.NacosLogLevelKey, "info"),
   106  		UpdateCacheWhenEmpty: url.GetParamBool(constant.NacosUpdateCacheWhenEmpty, true),
   107  	}
   108  	return serverConfigs, clientConfig, nil
   109  }
   110  
   111  // NewNacosClient create an instance with the config
   112  func NewNacosClient(rc *config.RemoteConfig) (*nacosClient.NacosNamingClient, error) {
   113  	url, err := rc.ToURL()
   114  	if err != nil {
   115  		return nil, err
   116  	}
   117  	scs, cc, err := GetNacosConfig(url)
   118  
   119  	if err != nil {
   120  		return nil, err
   121  	}
   122  	clientName := url.GetParam(constant.ClientNameKey, "")
   123  	if len(clientName) <= 0 {
   124  		return nil, perrors.New("nacos client name must set")
   125  	}
   126  	return nacosClient.NewNacosNamingClient(clientName, true, scs, cc)
   127  }
   128  
   129  // NewNacosClientByURL created
   130  func NewNacosClientByURL(url *common.URL) (*nacosClient.NacosNamingClient, error) {
   131  	scs, cc, err := GetNacosConfig(url)
   132  	if err != nil {
   133  		return nil, err
   134  	}
   135  	clientName := url.GetParam(constant.ClientNameKey, "")
   136  	if len(clientName) <= 0 {
   137  		return nil, perrors.New("nacos client name must set")
   138  	}
   139  	logger.Infof("[Nacos Client] New nacos client with config = %+v", scs)
   140  	return nacosClient.NewNacosNamingClient(clientName, true, scs, cc)
   141  }