google的grpc在golang中的使用

GRPC是google開源的一個高性能、跨語言的RPC框架,基於HTTP2協議,基於protobuf 3.x,基於Netty 4.x。java

前面寫過一篇golang標準庫的rpc包的用法,這篇文章接着講一下google的grpc。git

介紹

在 gRPC 裏客戶端應用能夠像調用本地對象同樣直接調用另外一臺不一樣的機器上服務端應用的方法,使得您可以更容易地建立分佈式應用和服務。github

image

使用grpc的優勢不少,支持多種語言,二進制的數據能夠加快傳輸速度,基於http2的多路複用能夠減小服務之間的鏈接次數,和函數同樣的調用方式也有效的提高了開發效率。golang

grpc提供有go版本,下面介紹一下grpc在golang中的使用。服務器

安裝

grpc支持1.5及以上版本。框架

用如下命令安裝grpc-go:tcp

go get google.golang.org/grpc

安裝Protocol Buffers v3分佈式

https://github.com/google/protobuf/releases下載最新的穩定的版本,而後解壓縮,把裏面的文件放到$PATH中。ide

安裝插件函數

go get -u github.com/golang/protobuf/{proto,protoc-gen-go}

別忘了將$GOPATH/bin添加到$PATH中:

export PATH=$PATH:$GOPATH/bin

示例

示例代碼獲取地址:https://github.com/andyidea/go-example

代碼文件結構以下

├── bin
│   ├── grpc-client
│   └── grpc-server
└── src
    └── grpc-helloworld
        ├── greeter_client
        │   └── main.go
        ├── greeter_server
        │   └── main.go
        └── helloworld
            ├── helloworld.pb.go
            └── helloworld.proto

grpc-helloworld裏有三個包,greeter_client是客戶端代碼,greeter_server是服務端代碼,helloworld是協議文件。

先看下協議。

helloworld.proto

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

協議中定義了兩個結構體HelloRequest和HelloReply,還有一個函數SayHello,函數的參數是HelloRequest,返回HelloReply。

src/下用下面命令生成協議的go文件:

protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld

這樣就生成了helloworld.pb.go協議文件。

接着咱們看下服務器端的代碼:

package main

import (
    "log"
    "net"

    "golang.org/x/net/context"
    "google.golang.org/grpc"
    pb "grpc-helloworld/helloworld"
    "google.golang.org/grpc/reflection"
)

const (
    port = ":50051"
)

// server is used to implement helloworld.GreeterServer.
type server struct{}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

func main() {
    lis, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    // Register reflection service on gRPC server.
    reflection.Register(s)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

服務器端主要邏輯就是實現以前協議中的SayHello方法,這裏是將字符串Hello和參數拼接在一塊兒返回。

協議生成的go文件給了一個RegisterGreeterServer方法,咱們用這個方法綁定實現函數的結構體和server。

而後是客戶端代碼:

package main

import (
    "log"
    "os"

    "golang.org/x/net/context"
    "google.golang.org/grpc"
    pb "grpc-helloworld/helloworld"
)

const (
    address     = "localhost:50051"
    defaultName = "world"
)

func main() {
    // Set up a connection to the server.
    conn, err := grpc.Dial(address, grpc.WithInsecure())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()
    c := pb.NewGreeterClient(conn)

    // Contact the server and print out its response.
    name := defaultName
    if len(os.Args) > 1 {
        name = os.Args[1]
    }
    r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
    if err != nil {
        log.Fatalf("could not greet: %v", err)
    }
    log.Printf("Greeting: %s", r.Message)
}

客戶端的思路也很清晰,創建一個rpc客戶端鏈接,將這個鏈接用pb.NewGreeterClient和協議綁定,返回一個client對象,用這個對象就能夠調用遠程的函數了。

調用輸出以下:

Greeting: Hello world

示例到此結束。示例代碼獲取地址:https://github.com/andyidea/go-example

相關文章
相關標籤/搜索