go-microv2 简单案例

1.服务端向服务中心注册

1.1 环境

go version go1.13.6 darwin/amd64

vscode1.41.6

Consul v1.8.0

工程结构

image-20200623195649280.png

1.2:proto

syntax = "proto3";

package proto;


service Greeter {
    rpc HelloTest (SayRequest) returns (SayResponse);
}

message  SayRequest{
    string name = 1;
}

message SayResponse{
    string greeting = 2;
}

1.3服务端代码


package main

import (
    "context"
    "fmt"
    "vscode/consul-demo01-provider/proto"

    "github.com/micro/go-micro/v2"
    _ "github.com/micro/go-plugins/registry/consul/v2"
)

type Greeter struct {
}

func (g *Greeter) HelloTest(ctx context.Context, req *proto.SayRequest, resp *proto.SayResponse) error {
    fmt.Println("recived data")
    resp.Greeting = req.Name + "===="
    return nil
}

func main() {

  //micro.Name服务端向consul注册服务名称 客户端需要通过该名称来进行调用
    service := micro.NewService(micro.Name("greeter"))
    service.Init()

    proto.RegisterGreeterHandler(service.Server(), new(Greeter))

    if err := service.Run(); err != nil {
        fmt.Println(err)
    }
}

服务端启动命定

go run main.go --registry=consul --server_address=localhost:8888

2.客户端代码

image-20200623200028791.png

2.1客户端代码

package main

import (
    "fmt"
    "vscode/consul-demo01-consumer/proto"

    "github.com/micro/go-micro/v2"
    _ "github.com/micro/go-plugins/registry/consul/v2"
    "golang.org/x/net/context"
)

func main() {
    service := micro.NewService(
        micro.Name("client.service"),
    )

    service.Init()

    greeter := proto.NewGreeterService("greeter", service.Client())

    rsp, err := greeter.HelloTest(context.TODO(), &proto.SayRequest{
        Name: "Hello test",
    })

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(rsp.GetGreeting)
}

客户端启动命定

go run main.go --registry=consul

服务端源代码

客户端源代码

你可能感兴趣的:(go-microv2 简单案例)