安装 gRPC
使用如下命令进行gRPC安装:
go get google.golang.org/grpc
安装 Protocol Buffers v3
安装该协议编译器用来生成 gRPC 服务代码。最简便的方法是在https://github.com/google/protobuf/releases下载一个二进制压缩包。解压后加入环境变量,如下:
export PATH=$PATH:执行路径 (linux下)
set PATH=%PATH%;执行路径 (windows下)
执行以下命令安装该协议插件:
go get github.com/golang/protobuf/proto
go get github.com/golang/protobuf/protoc-gen-go
在src目录下目录“helloworld”并新建文件“helloworld.proto”,填写如下内容:
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.go
protoc --proto_path=src/helloworld --go_out=plugins=grpc:src/helloworld src/helloworld/helloworld.proto
客户端client.go代码如下:
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)
}
服务端server.go代码如下:
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
pb "helloworld"
)
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) {
log.Printf("Received: %v", in.Name)
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{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
有疑问加站长微信联系(非本文作者)