Go Micro(3)——開發(fā)微服務(wù)

Go Micro(3)——開發(fā)微服務(wù)

這是一個(gè)高等級(jí)的說明:怎樣使用 go-micro 來編寫微服務(wù),如果你想學(xué)習(xí)更多微服務(wù)的知識(shí)以及Micro的整體架構(gòu),參考以前的文章。

什么是 Go Micro?

Go Micro 是一個(gè)插件化的基礎(chǔ)框架,基于此可以構(gòu)建微服務(wù)。Micro 的設(shè)計(jì)哲學(xué)是『可插拔』的插件化架構(gòu)。在架構(gòu)之外,它默認(rèn)實(shí)現(xiàn)了 consul 作為服務(wù)發(fā)現(xiàn),通過 http 進(jìn)行通信,通過 protobufjson 進(jìn)行編解碼。我們一步步深入下去。

Go Micro 是:

  • 一個(gè)用 Golang 編寫的包
  • 一系列插件化的接口定義
  • 基于 RPC

Go Micro 為下面的模塊定義了接口:

  • 服務(wù)發(fā)現(xiàn)
  • 編解碼
  • 服務(wù)端、客戶端
  • 訂閱、發(fā)布消息

更詳細(xì)的說明可以在這里看到。

Go Micro 從一年多以前開始開發(fā),最初只是個(gè)人需求,很快我發(fā)現(xiàn)這對(duì)那些編寫微服務(wù)的程序員會(huì)有很大的價(jià)值。它基于我在不同的技術(shù)公司如 googlehailo 的開發(fā)經(jīng)驗(yàn)編寫而成。

就像前面提到的,Go Micro 是一個(gè) golang 編寫的插件化架構(gòu),專注于提供底層的接口定義和基礎(chǔ)工具。這些接口可以接納各種實(shí)現(xiàn)。比如 Registry 接口定義了服務(wù)發(fā)現(xiàn)的接口,默認(rèn)采用了 consul 作為服務(wù)發(fā)現(xiàn)的實(shí)現(xiàn),但也可以采用其他實(shí)現(xiàn)比如 etcdzookeeper 等,只要能滿足接口,就可以使用。

插件化的架構(gòu)意味著如果你想替換底層的實(shí)現(xiàn),你不需要修改任何底層的代碼。

編寫一個(gè)服務(wù)

如果你想直接看代碼,看這里:examples/service

頂層的 Service 接口是構(gòu)建服務(wù)的主要組件。它把底層的各個(gè)包需要實(shí)現(xiàn)的接口,做了一次封裝。

type Service interface {
    Init(...Option)
    Options() Options
    Client() client.Client
    Server() server.Server
    Run() error
    String() string
}

初始化

一個(gè)服務(wù)可以這樣創(chuàng)建 micro.NewService

import "github.com/micro/go-micro"

service := micro.NewService()

參數(shù)可以在創(chuàng)建時(shí)傳入

service := micro.NewService(
    micro.Name("greeter"),
    micro.Version("latest"),
)

所有可選的參數(shù)設(shè)置可以在這里看到

Go Micro 也提供了讀取命令行的方式

import (
    "github.com/micro/cli"
    "github.com/micro/go-micro"
)

service := micro.NewService(
    micro.Flags(
        cli.StringFlag{
            Name:  "environment",
            Usage: "The environment",
        },
    )
)

通過 service.Init 來解析參數(shù),附加的處理可以通過 micro.Action 解決

service.Init(
    micro.Action(func(c *cli.Context) {
        env := c.StringFlag("environment")
        if len(env) > 0 {
            fmt.Println("Environment set to", env)
        }
    }),
)

Go Micro 提供了提供了預(yù)定義的參數(shù),也會(huì)被 service.Init 解析,這里可以看到所有的 flag

定義 API

我們使用 protobuf 文件來定義服務(wù)的 API,這是一種方便且嚴(yán)格的定義方式,協(xié)議將會(huì)提供給服務(wù)端和客戶端。下面是一個(gè)協(xié)議的例子:greeter.proto

syntax = "proto3";

service Greeter {
    rpc Hello(HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
    string name = 1;
}

message HelloResponse {
    string greeting = 2;
}

這里定義了一個(gè)服務(wù)叫做 Greeter,它提供一個(gè)接口叫 Hello,它接受 HelloRequest 的請(qǐng)求,返回 HelloResponse。

生成 API 接口

我們使用 protocproto-gen-go 這兩個(gè)工具來生成代碼,Go Micro 也會(huì)生成客戶端代碼,減少工作量,這里需要使用我們 fork 并修改過的 github.com/micro/protobuf,與原始版本的區(qū)別是,fork 版本能生成客戶端代碼

go get github.com/micro/protobuf/{proto,protoc-gen-go}
protoc --go_out=plugins=micro:. greeter.proto

生成的代碼可以在 handler 中引用相應(yīng)的包進(jìn)行使用,下面是生成的一部分代碼

type HelloRequest struct {
    Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}

type HelloResponse struct {
    Greeting string `protobuf:"bytes,2,opt,name=greeting" json:"greeting,omitempty"`
}

// Client API for Greeter service

type GreeterClient interface {
    Hello(ctx context.Context, in *HelloRequest, opts ...client.CallOption) (*HelloResponse, error)
}


type greeterClient struct {
    c           client.Client
    serviceName string
}

func NewGreeterClient(serviceName string, c client.Client) GreeterClient {
    if c == nil {
        c = client.NewClient()
    }
    if len(serviceName) == 0 {
        serviceName = "greeter"
    }
    return &greeterClient{
        c:           c,
        serviceName: serviceName,
    }
}

func (c *greeterClient) Hello(ctx context.Context, in *HelloRequest, opts ...client.CallOption) (*HelloResponse, error) {
    req := c.c.NewRequest(c.serviceName, "Greeter.Hello", in)
    out := new(HelloResponse)
    err := c.c.Call(ctx, req, out, opts...)
    if err != nil {
        return nil, err
    }
    return out, nil
}

// Server API for Greeter service

type GreeterHandler interface {
    Hello(context.Context, *HelloRequest, *HelloResponse) error
}

func RegisterGreeterHandler(s server.Server, hdlr GreeterHandler) {
    s.Handle(s.NewHandler(&Greeter{hdlr}))
}

實(shí)現(xiàn) handler

服務(wù)端需要注冊(cè) handler 來處理請(qǐng)求,一個(gè) handler 是一個(gè)這樣的方法:

func(ctx context.Context, req interface{}, rsp interface{}) error

正如上面看到的,一個(gè) handler 實(shí)現(xiàn)了 API 協(xié)議中定義的接口

type GreeterHandler interface {
        Hello(context.Context, *HelloRequest, *HelloResponse) error
}

這里是一個(gè) Greeterhandler 實(shí)現(xiàn)

import proto "github.com/micro/micro/examples/service/proto"

type Greeter struct{}

func (g *Greeter) Hello(ctx context.Context, req *proto.HelloRequest, rsp *proto.HelloResponse) error {
    rsp.Greeting = "Hello " + req.Name
    return nil
}

handler 需要注冊(cè)到某個(gè)服務(wù)

service := micro.NewService(
    micro.Name("greeter"),
)

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

運(yùn)行服務(wù)

服務(wù)可以直接調(diào)用 server.Run() 來運(yùn)行,這會(huì)讓服務(wù)監(jiān)聽一個(gè)隨機(jī)端口,這個(gè)調(diào)用也會(huì)讓服務(wù)將自身注冊(cè)到注冊(cè)器,當(dāng)服務(wù)停止運(yùn)行時(shí),會(huì)在注冊(cè)器注銷自己。

完整的服務(wù)端

package main

import (
        "log"

        "github.com/micro/go-micro"
        proto "github.com/micro/go-micro/examples/service/proto"

        "golang.org/x/net/context"
)

type Greeter struct{}

func (g *Greeter) Hello(ctx context.Context, req *proto.HelloRequest, rsp *proto.HelloResponse) error {
        rsp.Greeting = "Hello " + req.Name
        return nil
}

func main() {
        service := micro.NewService(
                micro.Name("greeter"),
                micro.Version("latest"),
        )

        service.Init()

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

        if err := service.Run(); err != nil {
                log.Fatal(err)
        }
}

注意,服務(wù)發(fā)現(xiàn)機(jī)制需要首先運(yùn)行起來,這樣服務(wù)才能注冊(cè)到注冊(cè)器中,才能被客戶端發(fā)現(xiàn)。

編寫客戶端

client 包用于向服務(wù)端發(fā)起請(qǐng)求,當(dāng)你創(chuàng)建一個(gè)服務(wù),客戶端可以調(diào)用的接口已經(jīng)自動(dòng)生成了

調(diào)用上面的服務(wù)可以用下面的客戶端代碼

/ create the greeter client using the service name and client
greeter := proto.NewGreeterClient("greeter", service.Client())

// request the Hello method on the Greeter handler
rsp, err := greeter.Hello(context.TODO(), &proto.HelloRequest{
    Name: "John",
})
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(rsp.Greeter)

proto.NewGreeterClient 就是我們剛才生成的代碼,根據(jù)服務(wù)名稱發(fā)送請(qǐng)求。

完整的示例可以在這里看到:go-micro/examples/service

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 微服務(wù)工具箱 現(xiàn)在你也許聽到了這個(gè)新現(xiàn)象:微服務(wù)。如果你對(duì)此不熟悉也有興趣學(xué)習(xí),歡迎參考上一篇文章。 這篇文章我們...
    浮x塵閱讀 6,382評(píng)論 0 13
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,534評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,917評(píng)論 25 709
  • 他發(fā)一個(gè)吐血的表情,說沒事...... 我亦有些莫名其妙,想問因果又覺得無(wú)此必要,就閑扯一般和他聊聊各自的現(xiàn)狀。 ...
    小瓶蓋shy閱讀 328評(píng)論 1 1
  • 大一下, 無(wú)聊, 無(wú)語(yǔ), 無(wú)心, 開心, 開車, 開會(huì)。 不, 會(huì)變的。
    Aolando閱讀 163評(píng)論 0 0

友情鏈接更多精彩內(nèi)容