go-grpc Note2
参考链接:grpc.io
Note:(2023年7月13日),这一部分将涉及具体的rpc调用过程之分,一元/CS流方式,并且假定Note1
Quick Start
代码来源:grpc.io
项目目录:
├── client
│ └── client.go
├── README.md
├── routeguide
│ ├── route_guide_grpc.pb.go
│ ├── route_guide.pb.go
│ └── route_guide.proto
├── server
│ └── server.go
└── testdata
└── route_guide_db.json
Define Service (.proto/.pb.go)
于routeguide/route_guide.proto中定义RouteGuide服务,代码如下:
service RouteGuide {
// A simple RPC.获取给定位置的特征
rpc GetFeature(Point) returns (Feature) {}
// A server-to-client streaming RPC.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
// A client-to-server streaming RPC.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
// A Bidirectional streaming RPC.
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
}
其中包括一元/服务端流/客户端流/双向流工四种rpc调用方式,于.proto中能够轻松定义流方式,如ListFeatures
中定义其返回值为stream
,代表从Server
返回到Client
处的相应为流方式。
消息(Message)如下:
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
message Rectangle {
Point lo = 1;
Point hi = 2;
}
message Feature {
string name = 1;
Point location = 2;
}
message RouteNote {
Point location = 1;
string message = 2;
}
message RouteSummary {
int32 point_count = 1;
int32 feature_count = 2;
int32 distance = 3;
int32 elapsed_time = 4;
}
常规Message定义,不赘述。
像Note1中记录的,通过以下命令生成.pb.go文件:
$ protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
routeguide/route_guide.proto
其中,.pb.go
文件包含填充、序列化和检索请求和响应消息类型的所有ProtoBuffer代码;
_grpc.pb.go
包括一个接口,供Client/Server使用RouteGuide服务中定义的方法调用。个人认为该文件较为重要,因为包括服务接口定义,client
对应接口代码如下:
// RouteGuideClient is the client API for RouteGuide service.
type RouteGuideClient interface {
GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error)
ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error)
···
}
type routeGuideClient struct {
cc grpc.ClientConnInterface
}
...
// RouteGuideServer is the server API for RouteGuide service.
type RouteGuideServer interface {
GetFeature(context.Context, *Point) (*Feature, error)
ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error
...
}
type UnimplementedRouteGuideServer struct {
}
先看Server端如何调用RouteGuideSever
接口的
Server/server.go
Continue…