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