1.安装gRPC运行环境
go get google.golang.org/grpc
这里的grpc通俗来说就说用在代码里的一个类库,后面的例子可以看到。比较坑的是这里可能需要FQ.....
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 mainconst (
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 mainconst (
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.WithInsecure返回一个DialOption,它在传输过程中不保证安全。除非设置WithInsecure,否则grpc.Dial必须指定安全选项。
Note that transport security is required unless WithInsecure is set.
参考:
1.https://github.com/google/protobuf/releases【golang|linux下golang gRPC配置详解】转载于:https://www.cnblogs.com/xiaodeshan/p/7794874.html
2.http://www.cnblogs.com/YaoDD/p/5504881.html
推荐阅读
- c/c++|有感 Visual Studio 2015 RTM 简介 - 八年后回归 Dot Net,终于迎来了 Mvc 时代,盼走了 Web 窗体时代...
- C/C++|C/C++ basis 02
- 【golang】leetcode中级-字母异位词分组&无重复字符的最长子串
- Qt实战|Qt+OpenCV联合开发(二十一)--图像翻转与旋转
- Qt实战|Qt+OpenCV联合开发(十四)--图像感兴趣区域(ROI)的提取
- Qt实战|Qt+OpenCV联合开发(十三)--通道分离与合并
- opencv|Qt+OpenCV联合开发(十六)--图像几何形状绘制
- Qt实战|Qt+OpenCV联合开发(十七)--随机数与随机颜色
- 彻底理解Golang Map
- kratos线上开源年会它来啦~