• go的http插件实现服务消费


    下载插件

    go get github.com/micro/go-plugins

    导包

    myhttp"github.com/micro/go-plugins/client/http"
    1.注册服务
    import (
        "github.com/gin-gonic/gin"
        "github.com/micro/go-micro/registry"
        "github.com/micro/go-micro/web"
        "github.com/micro/go-plugins/registry/consul"
    )
    
    // 使用gin框架
    func main() {
        consulReg := consul.NewRegistry(
            registry.Addrs("127.0.0.1:8500"),
        )
        ginRouter := gin.Default()
        v1Group := ginRouter.Group("/v1")
        {
            v1Group.Handle("POST", "/prods", func(context *gin.Context) {
                context.JSON(200,
                    gin.H{
                        "data": NewProdList(5),
                    })
            })
        }
    
        web.NewService(web.Address(":8001"),
            web.Handler(ginRouter),
            web.Registry(consulReg),
            web.Name("product")).Run()
    
    }

    2.消费服务

    import (
        "context"
        "fmt"
        "github.com/micro/go-micro/client"
        "github.com/micro/go-micro/client/selector"
        "github.com/micro/go-micro/registry"
        myhttp "github.com/micro/go-plugins/client/http"
        "github.com/micro/go-plugins/registry/consul"
        _ "io/ioutil"
        "log"
        _ "net/http"
    )
    
    func callApi2(s selector.Selector) {
        myclient := myhttp.NewClient(
            client.Selector(s),
            client.ContentType("application/json"),
        )
       //参数1服务名称,参数2路由地址,参数3传递的参数
        req := myclient.NewRequest("product", "/v1/prods", nil)
        var rsp map[string]interface{}
      //req请求参数, rep返回参数 err :
    = myclient.Call(context.Background(), req, &rsp) if err != nil { log.Fatal(err) } fmt.Println(rsp) } func main() { consulReg := consul.NewRegistry( registry.Addrs("127.0.0.1:8500")) mySelector := selector.NewSelector( selector.Registry(consulReg), selector.SetStrategy(selector.RoundRobin), ) callApi2(mySelector) }
  • 相关阅读:
    第二章 Java程序设计环境
    第一章 Java程序设计概述
    (五)Java工程化--Jenkins
    (二)Java工程化--Maven实践
    (四)Java工程化--Git基础
    (三)Java工程化--Git起步
    (一)Java工程化--Maven基础
    codeblocks 中文编码问题
    win10安装virtualbox发生严重错误
    利用ssh传输文件
  • 原文地址:https://www.cnblogs.com/huqi96/p/14389467.html
Copyright © 2020-2023  润新知