gRPC在golang中的使用(客戶端)

安裝 gRPClinux

使用以下命令進行gRPC安裝:git

go get google.golang.org/grpc

安裝 Protocol Buffers v3github

安裝該協議編譯器用來生成 gRPC 服務代碼。最簡便的方法是在https://github.com/google/protobuf/releases下載一個二進制壓縮包。解壓後加入環境變量,以下:golang

export PATH=$PATH:執行路徑 (linux下)
set PATH=%PATH%;執行路徑   (windows下)

 執行如下命令安裝該協議插件:windows

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

在src目錄下目錄「helloworld」並新建文件「helloworld.proto」,填寫以下內容:google

syntax = "proto3";


package helloworld;

// 服務端定義
service Greeter {
// 服務端返饋信息方法
rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// 包含用戶名的請求信息
message HelloRequest {
string name = 1;
}

// 服務端響應信息
message HelloReply {
string message = 1;
}

在bin目錄下有"protoc-gen-go"的可執行文件時,設置GOPATH/bin至PATH:(注:在windows下設置GOPATH時不能帶雙引號,不然設置GOPATH/bin就會出現"[GOPATH/bin]"/bin的環境變量。插件

set PATH=%PATH%;%GOPATH%/bin

而後使用protoc命令,在src/helloworld目錄下生成helloworld.pb.gocode

protoc --proto_path=src/helloworld --go_out=plugins=grpc:src/helloworld src/helloworld/helloworld.proto

在"main.go"裏填寫以下代碼:server

package main

import (
	"log"
	"os"

	"golang.org/x/net/context"
	"google.golang.org/grpc"
    pb "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)
}

執行命令 go run main.go,執行結果以下:rpc

相關文章
相關標籤/搜索