grpc和protocol buffer使用

grpc

grpc是Google的rpc开源框架,它使用了protocol buffer(Google的另一个开源工具)作为接口定义语言和消息传递格式。

大概的使用方法是:

  1. 使用protocol buffer语言编写接口定义。
  2. 使用protocol buffer工具将接口编译成目标语言代码,包括服务端的接口框架和客户端的接口stub定义,数据的序列化和反序列化过程等通用代码。
  3. 开发人员在服务端编写接口实现。
  4. 开发人员在客户端调用接口函数。
    grpc允许定义4中接口函数:
//一个参数和一个返回值:
rpc SayHello(HelloRequest) returns (HelloResponse){
}
//一个参数和流式返回
rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse){
}
//流式参数和一个返回
rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse) {
}
//流式参数和流式返回
rpc LotsOfGreetings(stream HelloRequest) returns (stream  HelloResponse) {
}

一个例子:

syntax = "proto3";

service RouteGuide{
    rpc GetFeature(Point) returns (Feature) {}
    rpc ListFeatures(Rectangle) returns (stream Feature) {}
    rpc RecordRoute(stream Point) returns (RouteSummary) {}
    rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
}

这样一个文件,使用protoc 编译以后生成的go语言的服务端接口代码:

// RouteGuideServer is the server API for RouteGuide service.
type RouteGuideServer interface {
   
	GetFeature(context.Context, *Point) (*Feature, error)
	ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error
	RecordRoute(RouteGuide_RecordRouteServer) error
	RouteChat(RouteGuide_RouteChatServer) error
}

GetFeature是一个接受一个Point返回一个Feature值的普通接口,使用pb生成的函数拥有两个参数,context和*Point,其中context是为了同步调用的cancel功能实现。返回值有两个一个是定义的返回值*Feature,另外一个是error,这个error是用于返回grpc调用错误的,所有的grpc生成接口函数都有。

ListFeatures是接受一个Rectangle,返回一个Feature流的接口,使用pb生成的接口将返回的流使用参数传入,也就是*Rectangle是原来的参数,RouteGuide_ListFeaturesServer用于返回流数据。函数的返回值依旧是一个error。

type RouteGuide_ListFeaturesServer interface {
   
	Send(*Feature) error
	grpc.ServerStream
}

RecordRoute是一个接受一个流,返回一个值。pb生成的接口将返回值和流合并到一个接口中,返回值变成一个error。

type RouteGuide_RecordRouteServer interface {
   
	SendAndClose(*RouteSummary) error
	Recv() (*Point, error)
	grpc.ServerStream
}

RouteChat是一个双向流,pb生成接口同样合并为一个参数,返回error·。

type RouteGuide_RouteChatServer interface {
   
	Send(*RouteNote) error
	Recv() (*RouteNote, error)
	grpc.ServerStream
}

这些pb生成的接口实际上是封装了grpc.ServerStream的流发送和接受, grpc.ServerStream更底层的实现这里不讨论。

type RouteGuide_ListFeaturesServer interface {
   
	Send(*Feature) error
	grpc.ServerStream
}

type routeGuideListFeaturesServer struct {
   
	grpc.ServerStream
}

func (x *routeGuideListFeaturesServer
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值