天天看點

Go Micro 初探起步初探 Micro感謝

文章目錄

  • 起步
  • 初探 Micro
  • 感謝

起步

在使用 go-micro 之前,我們需要做一些環境準備。

$ go get github.com/micro/protoc-gen-micro/v2

$ go get -u github.com/golang/protobuf/protoc-gen-go
           

然後安裝 protoc,這是軟體下載下傳連接配接。我用的作業系統是 centos 7,是以下載下傳的是:protoc-3.11.4-linux-x86_64.zip。

$ uzip protoc-3.11.4-linux-x86_64.zip -d protoc
$ mv protoc /usr/local/
$ ln -s /usr/local/protoc/bin/protoc /usr/sbin
           

如果你在終端能夠正常使用 protoc (

protoc -h

)指令,那麼環境就準備 OK 了。

初探 Micro

第一步:建立項目目錄。

$ mkdir hello-world
$ cd hello-world && mkdir server client proto
$ go mod init hello-world
           

第二步:建立 greeter.proto (

vim proto/greeter.proto

)。

syntax="proto3";

package hello_world;
option go_package = "proto";

service Greeter {
    rpc Hello(Request) returns (Response) {}
}

message Request {
    string name = 1;
}

message Response {
    string msg = 1;
}
           

package hello_world

聲明項目名;

option go_package = "proto"

聲明 proto 的包名。

利用 protoc “解釋” proto 檔案:

$ protoc --proto_path=$GOPATH/src:. --micro_out=. --go_out=. proto/greeter.proto
           

第三步:編寫伺服器 server (

vim server/main.go

)。

package main

import (
    "context"
    "fmt"
    "hello-world/proto"

    "github.com/micro/go-micro/v2"
)

type Greeter struct{}

func (g *Greeter) Hello(ctx context.Context, req *proto.Request, rsp *proto.Response) error {
    rsp.Msg = "Name: " + req.Name // 對用戶端傳遞的字元串做處理
    return nil
}

func main() {
    // 建立伺服器
    service := micro.NewService(
        micro.Name("greeter"),
    )
    service.Init()
    // 注冊 handler
    proto.RegisterGreeterHandler(service.Server(), new(Greeter))

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

第四步:編寫用戶端 client (

vim client/main.go

)。

package main

import (
    "context"
    "fmt"
    "hello-world/proto"

    "github.com/micro/go-micro/v2"
)

func main() {
    service := micro.NewService(micro.Name("greeter.client"))
    service.Init()
    // 建立 greeter 用戶端
    greeter := proto.NewGreeterService("greeter", service.Client())
    // 調用 Greeter.Hello
    rsp, err := greeter.Hello(context.TODO(), &proto.Request{Name: "Zhong"})
    if err != nil {
        fmt.Println(err.Error())
    }
    fmt.Println(rsp.Msg)
}
           

第五步:啟動伺服器。

$ go run server/main.go
           

最後啟動用戶端:

$ go run client/main.go
           

如果不出意外,用戶端運作後列印 Name: Zhong 字樣。一個簡單的 micro 微服務就搭建好了。

感謝

  • 參考 gRPC in Golang
  • 參考 Micro Docs