Golang gRPC 示例

一、安裝gRPC runtimejava

go get google.golang.org/grpc

  

爲了自動生成Golang的gRPC代碼,須要安裝protocal buffers compiler以及對應的GoLang插件git

 

二、protocal buffer安裝github

從https://github.com/google/protobuf/releases下載安裝包,例如:protobuf-cpp-3.0.0-beta-3.zip,解壓後golang

./configure
make && make install

  

再添加環境變量:export LD_LIBRARY_PATH=/usr/local/lib,以後protoc命令便可運行bash

 

三、安裝GoLang protoc 插件服務器

go get -a github.com/golang/protobuf/protoc-gen-go

  

四、定義servicetcp

一個RPC service就是一個可以經過參數和返回值進行遠程調用的method,咱們能夠簡單地將它理解成一個函數。由於gRPC是經過將數據編碼成protocal buffer來實現傳輸的。所以,咱們經過protocal buffers interface definitioin language(IDL)來定義service method,同時將參數和返回值也定義成protocal buffer message類型。具體實現以下所示,包含下面代碼的文件叫helloworld.proto:函數

syntax = "proto3";

option java_package = "io.grpc.examples";

package helloworld;

// The greeter 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;
}

  

五、接着,根據上述定義的service,咱們能夠利用protocal buffer compiler ,即protoc生成相應的服務器端和客戶端的GoLang代碼。生成的代碼中包含了客戶端可以進行RPC的方法以及服務器端須要進行實現的接口。google

假設如今所在的目錄是$GOPATH/src/helloworld/helloworld,咱們將經過以下命令生成gRPC對應的GoLang代碼:編碼

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

  

此時,將在目錄下生成helloworld.pb.go文件。

 

六、接着,在目錄$GOPATH/src/helloworld/下建立server.go 和client.go,分別用於服務器和客戶端的實現。

package main 

// server.go

import (
	"log"
	"net"

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

const (
	port = ":50051"
)

type server struct {}

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.Fatal("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	s.Serve(lis)
}

  

  

package main 

//client.go

import (
	"log"
	"os"

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

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

func main() {
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		log.Fatal("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewGreeterClient(conn)

	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.Fatal("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r.Message)
}

  

這裏須要注意的是包pb是咱們以前生成的helloworld.pb.go所在的包,並不是必須如上述代碼所示在$GOPATH/src/helloworld/helloworld目錄下。

 

七、最後運行以下代碼進行演示便可

go run server.go
go run client.go
相關文章
相關標籤/搜索