go-grpc笔记2

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…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值