1.安裝gRPC運行環境
go get google.golang.org/grpc
這里的grpc通俗來說就說用在代碼里的一個類庫,后面的例子可以看到。比較坑的是這里可能需要翻牆.....
2.安裝protoc
這里需要安裝proto buffer
的編譯器。首先在官網下載,如c++版本的protobuf-cpp-3.4.1.tar.gz,解壓后進行編譯:
./configure
make && make install
3.安裝protoc-gen-go
go get -a github.com/golang/protobuf/protoc-gen-go
4.編寫proto文件
基於protobuf的跨語言的特性,不難想到它自己實現了一套數據類型。這里有一個簡單的例子
//testHello.proto
syntax = "proto3";
package protos;
// The service definition.
service Devops {
// 定義服務
rpc SayHello (HelloRequest) returns (Response) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message
message HelloReply {
string message = 1;
}
message Response {
enum StatusCode {
UNDEFINED = 0;
SUCCESS = 200;
FAILURE = 500;
}
StatusCode status = 1;
HelloReply msg = 2;
}
然后在終端自動生成pb.go:
protoc --go_out=plugins=grpc:. testHello.proto
5.編寫服務端
package main
const (
port = ":50051"
)
type myserver struct{}
//這里myserver實現了SayHello
func (s *myserver) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.Response, error) {
fmt.Print("receive " + in.Name)
return &pb.Response{
Status:pb.Response_SUCCESS,
Msg:&pb.HelloReply{Message:"receive " + in.Name},
}, nil
}
func main() {
//綁定端口
lis, err := net.Listen("tcp", port)
if err != nil{
log.Fatal("fail to listen")
}
s := grpc.NewServer()
pb.RegisterDevopsServer(s, &myserver{})
s.Serve(lis)
}
6.編寫客戶端
package main
const (
address = "localhost:50051"
)
func main() {
//grpc.WithInsecure()指定后才不會報錯
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil{
log.Fatal("error....", err)
}
c := pb.NewDevopsClient(conn)
res, _ := c.SayHello(context.Background(), &pb.HelloRequest{"eeee"})
fmt.Print(res)
}
WithInsecure returns a DialOption which disables transport security for this ClientConn.
Note that transport security is required unless WithInsecure is set.
WithInsecure返回一個DialOption,它在傳輸過程中不保證安全。除非設置WithInsecure,否則grpc.Dial必須指定安全選項。
參考:
1.https://github.com/google/protobuf/releases
2.http://www.cnblogs.com/YaoDD/p/5504881.html