美文网首页
Go调用注册到Nacos中的服务

Go调用注册到Nacos中的服务

作者: EasyNetCN | 来源:发表于2024-08-08 12:12 被阅读0次

服务调用客户端

package util

import (
    "fmt"
    "math/rand/v2"
    "net/http"
    "net/url"

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

type ServiceClient struct {
    namingClient naming_client.INamingClient
    webClient    *WebClient
}

func NewServiceClient(namingClient naming_client.INamingClient, webClient *WebClient) *ServiceClient {
    return &ServiceClient{
        namingClient: namingClient,
        webClient:    webClient,
    }
}

func (m *ServiceClient) Get(serviceName string, path string, urlValues url.Values) (int, []byte, error) {
    _, code, bytees, err := m.Do(serviceName, "GET", "application/json;charset=UTF-8", path, urlValues, nil)

    return code, bytees, err
}

func (m *ServiceClient) Post(serviceName string, path string, bodyValue any) (int, []byte, error) {
    _, code, bytees, err := m.Do(serviceName, "POST", "application/json;charset=UTF-8", path, nil, bodyValue)

    return code, bytees, err
}

func (m *ServiceClient) Put(serviceName string, path string, urlValues url.Values, bodyValue any) (int, []byte, error) {
    _, code, bytees, err := m.Do(serviceName, "PUT", "application/json;charset=UTF-8", path, urlValues, bodyValue)

    return code, bytees, err
}

func (m *ServiceClient) Delete(serviceName string, path string, urlValues url.Values, bodyValue any) (int, []byte, error) {
    _, code, bytees, err := m.Do(serviceName, "DELETE", "application/json;charset=UTF-8", path, urlValues, bodyValue)

    return code, bytees, err
}

func (m *ServiceClient) Do(
    serviceName string,
    method string,
    contentType string,
    path string, urlValues url.Values,
    bodyValue any) (*http.Response, int, []byte, error) {
    serviceUrl, err := m.GetServiceUrl(serviceName)

    if err != nil {
        return nil, 0, nil, err
    }

    return m.webClient.Do(method, contentType, serviceUrl, path, urlValues, bodyValue)
}

func (m *ServiceClient) GetServiceUrl(serviceName string) (string, error) {
    service, err := m.namingClient.GetService(vo.GetServiceParam{ServiceName: serviceName})

    if err != nil {
        return "", err
    }

    if !service.Valid {
        return "", fmt.Errorf("服务(%s)不存在", serviceName)
    }

    urls := make([]string, 0, len(service.Hosts))

    for _, instance := range service.Hosts {
        if instance.Enable && instance.Healthy {
            urls = append(urls, fmt.Sprintf("http://%s:%d", instance.Ip, instance.Port))
        }
    }

    if len(urls) == 0 {
        return "", fmt.Errorf("服务(%s)没有可用的实例", serviceName)
    }

    if len(urls) == 1 {
        return urls[0], nil
    }

    return urls[rand.IntN(len(urls))], nil
}

Http请求客户端

package util

import (
    "bytes"
    "encoding/json"
    "io"
    "net/http"
    "net/url"
    "strings"
)

type WebClient struct {
    Client *http.Client
}

func NewWebClient(client *http.Client) *WebClient {
    return &WebClient{Client: client}
}

func (m *WebClient) Get(baseUrl string, path string, urlValues url.Values) (int, []byte, error) {
    _, code, bytees, err := m.Do("GET", "application/json;charset=UTF-8", baseUrl, path, urlValues, nil)

    return code, bytees, err
}

func (m *WebClient) GetRes(baseUrl string, path string, urlValues url.Values) (*http.Response, int, []byte, error) {
    res, code, bytees, err := m.Do("GET", "application/json;charset=UTF-8", baseUrl, path, urlValues, nil)

    return res, code, bytees, err
}

func (m *WebClient) Post(baseUrl string, path string, bodyValue interface{}) (int, []byte, error) {
    _, code, bytees, err := m.Do("POST", "application/json;charset=UTF-8", baseUrl, path, nil, bodyValue)

    return code, bytees, err
}

func (m *WebClient) Put(baseUrl string, path string, urlValues url.Values, bodyValue interface{}) (int, []byte, error) {
    _, code, bytees, err := m.Do("PUT", "application/json;charset=UTF-8", baseUrl, path, urlValues, bodyValue)

    return code, bytees, err
}

func (m *WebClient) Delete(baseUrl string, path string, urlValues url.Values, bodyValue interface{}) (int, []byte, error) {
    _, code, bytees, err := m.Do("DELETE", "application/json;charset=UTF-8", baseUrl, path, urlValues, bodyValue)

    return code, bytees, err
}

func (m *WebClient) Do(method string, contentType string, baseUrl string, path string, urlValues url.Values, bodyValue interface{}) (*http.Response, int, []byte, error) {
    bodyValueBytes, err1 := json.Marshal(bodyValue)

    if err1 != nil {
        return nil, 0, nil, err1
    }

    if req, err := http.NewRequest(method, m.url(baseUrl, path, urlValues), bytes.NewReader(bodyValueBytes)); err != nil {
        return nil, 0, nil, err
    } else {
        return m.doRequest(req, contentType)
    }
}

func (m *WebClient) url(baseUrl string, path string, urlValues url.Values) string {
    result, _ := url.JoinPath(baseUrl, path)

    sb := new(strings.Builder)

    sb.WriteString(result)

    if len(urlValues) > 0 {
        sb.WriteString("?")
        sb.WriteString(urlValues.Encode())
    }

    return sb.String()

}

func (m *WebClient) doRequest(req *http.Request, contentType string) (*http.Response, int, []byte, error) {
    req.Header.Set("Content-Type", contentType)

    if res, err := m.Client.Do(req); err != nil {
        return res, res.StatusCode, nil, err
    } else {
        if resBytes, err := io.ReadAll(res.Body); err != nil {
            return res, res.StatusCode, nil, err
        } else {
            return res, res.StatusCode, resBytes, nil
        }
    }
}

相关文章

  • Nacos服务注册中心替换Eureka

    最近部署了dubbo+nacos集群服务,以前的微服务是注册到eureka中的,当调用其他微服务的时候不太方便,于...

  • Nacos客户端心跳续约

    业务提供者引入nacos客户端sdk,通过这个sdk向nacos服务器注册服务,这个服务让消费者调用。 Nacos...

  • 从实现原理来讲,Nacos 为什么这么强?

    今天来分享一下Nacos注册中心的底层原理,从服务注册到服务发现,非常细致 一. Nacos介绍 再讲Nacos之...

  • Nacos配置中心

    一、使用步骤 1.在要注册到Nacos配置中的微服务中添加nacos-config依赖 2.在微服务的 /src/...

  • Nacos注册中心通过FeginAB跨服务调用

    简介 Nacos 已经作为注册中心了,现在咱们实现A 服务通过注册中心调用B服务,本文通过Fegin实现。 B服务...

  • 7.nacos实现服务调用

    将商品微服务注册到nacos 接下来开始修改shop-product模块的代码,将其注册到nacos服务上 1.在...

  • 03 nacos-远程调用

    上一节我们在nacos上注册了服务,这一节我们尝试去调用该服务。 1、前提约束 已经在nacos上注册了一个服务 ...

  • Nacos基础-服务注册&服务调用

    前言:本文是基础应用Nacos的文章,全是基础内容,已熟悉的建议跳过。 零、本文纲要 一、基础的服务调用二、Nac...

  • 32 服务发现与注册 nacos

    Nacos 分布式注册与发现功能|分布式配置中心产生背景rpc远程调用中。服务的url 的治理rpc的远程调用框架...

  • nacos-服务注册发现源码分析-启动注册-02

    通过对nacos 作为注册中心的简单使用,我们观察到一个现象,就是服务启动后就会注册到nacos服务端。于是我们就...

网友评论

      本文标题:Go调用注册到Nacos中的服务

      本文链接:https://www.haomeiwen.com/subject/yhackjtx.html