google的grpc在golang中的使用


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

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

介紹

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

image

使用grpc的優點很多,支持多種語言,二進制的數據可以加快傳輸速度,基於http2的多路復用可以減少服務之間的連接次數,和函數一樣的調用方式也有效的提升了開發效率。

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

安裝

grpc支持1.5及以上版本。

用以下命令安裝grpc-go:

go get google.golang.org/grpc

安裝Protocol Buffers v3

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

安裝插件

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM