{ "ID":"312822199204085698", "gender":0, "major":"math", "name":18 }
package tutotial; // .proto文件以一個package聲明開始。這個聲明是爲了防止不一樣項目之間的命名衝突。 message Student{ // message 一個消息就是某些類型的字段的集合,能夠嵌套使用其餘的消息類型。 requried uint64 id = 1; // requried 是必須提供的字段,否者對應的消息就會被認爲是未初始化的。 requried string name = 2; opitional string email = 3; // 字段值指定與否均可以, 若是沒有指定一個optional的字段值,他會使用默認值,若是沒有默認值,系統默認值會使用: 數據類型的默認值爲0,string的默認值爲空字符串,bool的默認值爲false,對嵌套消息來講,其默認值老是消息的默認實例或者原型。 // 關於標識: '=1'的標誌指出了該字段在二進制編碼中使用的惟一"標識(tag)"; // 標識號1~15編碼所須要的字節數比更大的標識號使用的字節數要少1個,因此,若是你想尋求優化,能夠爲常用或重複的項採用1~15的標識(tag),其餘常用的optional項採用>=16的標識(tag)。 // 在重複的字段中,每一項都要求重編碼標識(tag number),因此重複的字段特別適用於這種優化。 enum PhoneType { MOBILE = 0; HOME = 1; } message PhoneNumber { requried string number = 1; opitional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; //字段會重複N次(N能夠爲0)。重複的值的順序將被保存在protocol buffer中。你只要將重複的字段視爲動態大小的數組就能夠了。 }
This tutorial provides a basic C++ programmer's introduction to working with
gRPC. By walking through this example you'll learn how to:java
.proto
file.It assumes that you are familiar with
protocol buffers.
Note that the example in this tutorial uses the proto3 version of the protocol
buffers language, which is currently in alpha release: you can find out more in
the proto3 language guide
and see the release notes for the
new version in the protocol buffers Github repository.c++
Our example is a simple route mapping application that lets clients get
information about features on their route, create a summary of their route, and
exchange route information such as traffic updates with the server and other
clients.git
With gRPC we can define our service once in a .proto
file and implement clients
and servers in any of gRPC's supported languages, which in turn can be run in
environments ranging from servers inside Google to your own tablet - all the
complexity of communication between different languages and environments is
handled for you by gRPC. We also get all the advantages of working with protocol
buffers, including efficient serialization, a simple IDL, and easy interface
updating.github
The example code for our tutorial is in examples/cpp/route_guide.
You also should have the relevant tools installed to generate the server and
client interface code - if you don't already, follow the setup instructions in
BUILDING.md.正則表達式
Our first step is to define the gRPC service and the method request and
response types using
protocol buffers.
You can see the complete .proto
file in
examples/protos/route_guide.proto
.shell
To define a service, you specify a named service
in your .proto
file:json
service RouteGuide { ... }
Then you define rpc
methods inside your service definition, specifying their
request and response types. gRPC lets you define four kinds of service method,
all of which are used in the RouteGuide
service:數組
// Obtains the feature at a given position. rpc GetFeature(Point) returns (Feature) {}
stream
// Obtains the Features available within the given Rectangle. Results are // streamed rather than returned at once (e.g. in a response message with a // repeated field), as the rectangle may cover a large area and contain a // huge number of features. rpc ListFeatures(Rectangle) returns (stream Feature) {}
stream
keyword before the request type.// Accepts a stream of Points on a route being traversed, returning a // RouteSummary when traversal is completed. rpc RecordRoute(stream Point) returns (RouteSummary) {}
stream
// Accepts a stream of RouteNotes sent while a route is being traversed, // while receiving other RouteNotes (e.g. from other users). rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
Our .proto
file also contains protocol buffer message type definitions for all
the request and response types used in our service methods - for example, here's
the Point
message type:服務器
// Points are represented as latitude-longitude pairs in the E7 representation // (degrees multiplied by 10**7 and rounded to the nearest integer). // Latitudes should be in the range +/- 90 degrees and longitude should be in // the range +/- 180 degrees (inclusive). message Point { int32 latitude = 1; int32 longitude = 2; }
Next we need to generate the gRPC client and server interfaces from our .proto
service definition. We do this using the protocol buffer compiler protoc
with
a special gRPC C++ plugin.網絡
For simplicity, we've provided a Makefile that runs
protoc
for you with the appropriate plugin, input, and output (if you want to
run this yourself, make sure you've installed protoc and followed the gRPC code
installation instructions first):
$ make route_guide.grpc.pb.cc route_guide.pb.cc
which actually runs:
$ protoc -I ../../protos --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ../../protos/route_guide.proto $ protoc -I ../../protos --cpp_out=. ../../protos/route_guide.proto
Running this command generates the following files in your current directory:
route_guide.pb.h
, the header which declares your generated message classesroute_guide.pb.cc
, which contains the implementation of your message classesroute_guide.grpc.pb.h
, the header which declares your generated serviceroute_guide.grpc.pb.cc
, which contains the implementation of your serviceThese contain:
RouteGuide
that contains
RouteGuide
service.RouteGuide
service.First let's look at how we create a RouteGuide
server. If you're only
interested in creating gRPC clients, you can skip this section and go straight
to Creating the client (though you might find it interesting
anyway!).
There are two parts to making our RouteGuide
service do its job:
You can find our example RouteGuide
server in
route_guide/route_guide_server.cc. Let's
take a closer look at how it works.
As you can see, our server has a RouteGuideImpl
class that implements the
generated RouteGuide::Service
interface:
class RouteGuideImpl final : public RouteGuide::Service { ... }
In this case we're implementing the synchronous version of RouteGuide
, which
provides our default gRPC server behaviour. It's also possible to implement an
asynchronous interface, RouteGuide::AsyncService
, which allows you to further
customize your server's threading behaviour, though we won't look at this in
this tutorial.
RouteGuideImpl
implements all our service methods. Let's look at the simplest
type first, GetFeature
, which just gets a Point
from the client and returns
the corresponding feature information from its database in a Feature
.
Status GetFeature(ServerContext* context, const Point* point, Feature* feature) override { feature->set_name(GetFeatureName(*point, feature_list_)); feature->mutable_location()->CopyFrom(*point); return Status::OK; }
The method is passed a context object for the RPC, the client's Point
protocol
buffer request, and a Feature
protocol buffer to fill in with the response
information. In the method we populate the Feature
with the appropriate
information, and then return
with an OK
status to tell gRPC that we've
finished dealing with the RPC and that the Feature
can be returned to the
client.
Now let's look at something a bit more complicated - a streaming RPC.
ListFeatures
is a server-side streaming RPC, so we need to send back multiple
Feature
s to our client.
Status ListFeatures(ServerContext* context, const Rectangle* rectangle, ServerWriter<Feature>* writer) override { auto lo = rectangle->lo(); auto hi = rectangle->hi(); long left = std::min(lo.longitude(), hi.longitude()); long right = std::max(lo.longitude(), hi.longitude()); long top = std::max(lo.latitude(), hi.latitude()); long bottom = std::min(lo.latitude(), hi.latitude()); for (const Feature& f : feature_list_) { if (f.location().longitude() >= left && f.location().longitude() <= right && f.location().latitude() >= bottom && f.location().latitude() <= top) { writer->Write(f); } } return Status::OK; }
As you can see, instead of getting simple request and response objects in our
method parameters, this time we get a request object (the Rectangle
in which
our client wants to find Feature
s) and a special ServerWriter
object. In the
method, we populate as many Feature
objects as we need to return, writing them
to the ServerWriter
using its Write()
method. Finally, as in our simple RPC,
we return Status::OK
to tell gRPC that we've finished writing responses.
If you look at the client-side streaming method RecordRoute
you'll see it's
quite similar, except this time we get a ServerReader
instead of a request
object and a single response. We use the ServerReader
s Read()
method to
repeatedly read in our client's requests to a request object (in this case a
Point
) until there are no more messages: the server needs to check the return
value of Read()
after each call. If true
, the stream is still good and it
can continue reading; if false
the message stream has ended.
while (stream->Read(&point)) { ...//process client input }
Finally, let's look at our bidirectional streaming RPC RouteChat()
.
Status RouteChat(ServerContext* context, ServerReaderWriter<RouteNote, RouteNote>* stream) override { std::vector<RouteNote> received_notes; RouteNote note; while (stream->Read(¬e)) { for (const RouteNote& n : received_notes) { if (n.location().latitude() == note.location().latitude() && n.location().longitude() == note.location().longitude()) { stream->Write(n); } } received_notes.push_back(note); } return Status::OK; }
This time we get a ServerReaderWriter
that can be used to read and write
messages. The syntax for reading and writing here is exactly the same as for our
client-streaming and server-streaming methods. Although each side will always
get the other's messages in the order they were written, both the client and
server can read and write in any order — the streams operate completely
independently.
Once we've implemented all our methods, we also need to start up a gRPC server
so that clients can actually use our service. The following snippet shows how we
do this for our RouteGuide
service:
void RunServer(const std::string& db_path) { std::string server_address("0.0.0.0:50051"); RouteGuideImpl service(db_path); ServerBuilder builder; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; server->Wait(); }
As you can see, we build and start our server using a ServerBuilder
. To do this, we:
RouteGuideImpl
.ServerBuilder
class.AddListeningPort()
method.BuildAndStart()
on the builder to create and start an RPC server forWait()
on the server to do a blocking wait until process is killed orShutdown()
is called.In this section, we'll look at creating a C++ client for our RouteGuide
service. You can see our complete example client code in
route_guide/route_guide_client.cc.
To call service methods, we first need to create a stub.
First we need to create a gRPC channel for our stub, specifying the server
address and port we want to connect to without SSL:
grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials());
Now we can use the channel to create our stub using the NewStub
method
provided in the RouteGuide
class we generated from our .proto
.
public: RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db) : stub_(RouteGuide::NewStub(channel)) { ... }
Now let's look at how we call our service methods. Note that in this tutorial
we're calling the blocking/synchronous versions of each method: this means
that the RPC call waits for the server to respond, and will either return a
response or raise an exception.
Calling the simple RPC GetFeature
is nearly as straightforward as calling a
local method.
Point point; Feature feature; point = MakePoint(409146138, -746188906); GetOneFeature(point, &feature); ... bool GetOneFeature(const Point& point, Feature* feature) { ClientContext context; Status status = stub_->GetFeature(&context, point, feature); ... }
As you can see, we create and populate a request protocol buffer object (in our
case Point
), and create a response protocol buffer object for the server to
fill in. We also create a ClientContext
object for our call - you can
optionally set RPC configuration values on this object, such as deadlines,
though for now we'll use the default settings. Note that you cannot reuse this
object between calls. Finally, we call the method on the stub, passing it the
context, request, and response. If the method returns OK
, then we can read the
response information from the server from our response object.
std::cout << "Found feature called " << feature->name() << " at " << feature->location().latitude()/kCoordFactor_ << ", " << feature->location().longitude()/kCoordFactor_ << std::endl;
Now let's look at our streaming methods. If you've already read Creating the
server some of this may look very familiar - streaming RPCs are
implemented in a similar way on both sides. Here's where we call the server-side
streaming method ListFeatures
, which returns a stream of geographical
Feature
s:
std::unique_ptr<ClientReader<Feature> > reader( stub_->ListFeatures(&context, rect)); while (reader->Read(&feature)) { std::cout << "Found feature called " << feature.name() << " at " << feature.location().latitude()/kCoordFactor_ << ", " << feature.location().longitude()/kCoordFactor_ << std::endl; } Status status = reader->Finish();
Instead of passing the method a context, request, and response, we pass it a
context and request and get a ClientReader
object back. The client can use the
ClientReader
to read the server's responses. We use the ClientReader
s
Read()
method to repeatedly read in the server's responses to a response
protocol buffer object (in this case a Feature
) until there are no more
messages: the client needs to check the return value of Read()
after each
call. If true
, the stream is still good and it can continue reading; if
false
the message stream has ended. Finally, we call Finish()
on the stream
to complete the call and get our RPC status.
The client-side streaming method RecordRoute
is similar, except there we pass
the method a context and response object and get back a ClientWriter
.
std::unique_ptr<ClientWriter<Point> > writer( stub_->RecordRoute(&context, &stats)); for (int i = 0; i < kPoints; i++) { const Feature& f = feature_list_[feature_distribution(generator)]; std::cout << "Visiting point " << f.location().latitude()/kCoordFactor_ << ", " << f.location().longitude()/kCoordFactor_ << std::endl; if (!writer->Write(f.location())) { // Broken stream. break; } std::this_thread::sleep_for(std::chrono::milliseconds( delay_distribution(generator))); } writer->WritesDone(); Status status = writer->Finish(); if (status.IsOk()) { std::cout << "Finished trip with " << stats.point_count() << " points\n" << "Passed " << stats.feature_count() << " features\n" << "Travelled " << stats.distance() << " meters\n" << "It took " << stats.elapsed_time() << " seconds" << std::endl; } else { std::cout << "RecordRoute rpc failed." << std::endl; }
Once we've finished writing our client's requests to the stream using Write()
,
we need to call WritesDone()
on the stream to let gRPC know that we've
finished writing, then Finish()
to complete the call and get our RPC status.
If the status is OK
, our response object that we initially passed to
RecordRoute()
will be populated with the server's response.
Finally, let's look at our bidirectional streaming RPC RouteChat()
. In this
case, we just pass a context to the method and get back a ClientReaderWriter
,
which we can use to both write and read messages.
std::shared_ptr<ClientReaderWriter<RouteNote, RouteNote> > stream( stub_->RouteChat(&context));
The syntax for reading and writing here is exactly the same as for our
client-streaming and server-streaming methods. Although each side will always
get the other's messages in the order they were written, both the client and
server can read and write in any order — the streams operate completely
independently.
Build client and server:
$ make
Run the server, which will listen on port 50051:
$ ./route_guide_server
Run the client (in a different terminal):
$ ./route_guide_client
Make sure you have installed gRPC on your system. Follow the
BUILDING.md instructions.
The example code for this and our other examples lives in the examples
directory. Clone this repository to your local machine by running the
following command:
$ git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc
Change your current directory to examples/cpp/helloworld
$ cd examples/cpp/helloworld/
The first step in creating our example is to define a service: an RPC
service specifies the methods that can be called remotely with their parameters
and return types. As you saw in the
overview above, gRPC does this using protocol
buffers. We
use the protocol buffers interface definition language (IDL) to define our
service methods, and define the parameters and return
types as protocol buffer message types. Both the client and the
server use interface code generated from the service definition.
Here's our example service definition, defined using protocol buffers IDL in
helloworld.proto. The Greeting
service has one method, hello
, that lets the server receive a single
HelloRequest
message from the remote client containing the user's name, then send back
a greeting in a single HelloReply
. This is the simplest type of RPC you
can specify in gRPC - we'll look at some other types later in this document.
syntax = "proto3"; option java_package = "ex.grpc"; package helloworld; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; }
Once we've defined our service, we use the protocol buffer compiler
protoc
to generate the special client and server code we need to create
our application. The generated code contains both stub code for clients to
use and an abstract interface for servers to implement, both with the method
defined in our Greeting
service.
To generate the client and server side interfaces:
$ make helloworld.grpc.pb.cc helloworld.pb.cc
Which internally invokes the proto-compiler as:
$ protoc -I ../../protos/ --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin ../../protos/helloworld.proto $ protoc -I ../../protos/ --cpp_out=. ../../protos/helloworld.proto
Create a channel. A channel is a logical connection to an endpoint. A gRPC
channel can be created with the target address, credentials to use and
arguments as follows
auto channel = CreateChannel("localhost:50051", InsecureChannelCredentials());
Create a stub. A stub implements the rpc methods of a service and in the
generated code, a method is provided to created a stub with a channel:
auto stub = helloworld::Greeter::NewStub(channel);
Make a unary rpc, with ClientContext
and request/response proto messages.
ClientContext context; HelloRequest request; request.set_name("hello"); HelloReply reply; Status status = stub->SayHello(&context, request, &reply);
Check returned status and response.
if (status.ok()) { // check reply.message() } else { // rpc failed. }
For a working example, refer to greeter_client.cc.
Implement the service interface
class GreeterServiceImpl final : public Greeter::Service { Status SayHello(ServerContext* context, const HelloRequest* request, HelloReply* reply) override { std::string prefix("Hello "); reply->set_message(prefix + request->name()); return Status::OK; } };
Build a server exporting the service
GreeterServiceImpl service; ServerBuilder builder; builder.AddListeningPort("0.0.0.0:50051", grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart());
For a working example, refer to greeter_server.cc.
gRPC uses CompletionQueue
API for asynchronous operations. The basic work flow
is
CompletionQueue
to a rpc callvoid*
tagCompletionQueue::Next
to wait for operations to complete. If a tagThe channel and stub creation code is the same as the sync client.
Initiate the rpc and create a handle for the rpc. Bind the rpc to a
CompletionQueue
.
CompletionQueue cq; auto rpc = stub->AsyncSayHello(&context, request, &cq);
Ask for reply and final status, with a unique tag
Status status; rpc->Finish(&reply, &status, (void*)1);
Wait for the completion queue to return the next tag. The reply and status are
ready once the tag passed into the corresponding Finish()
call is returned.
void* got_tag; bool ok = false; cq.Next(&got_tag, &ok); if (ok && got_tag == (void*)1) { // check reply and status }
For a working example, refer to greeter_async_client.cc.
The server implementation requests a rpc call with a tag and then wait for the
completion queue to return the tag. The basic flow is
Build a server exporting the async service
helloworld::Greeter::AsyncService service; ServerBuilder builder; builder.AddListeningPort("0.0.0.0:50051", InsecureServerCredentials()); builder.RegisterService(&service); auto cq = builder.AddCompletionQueue(); auto server = builder.BuildAndStart();
Request one rpc
ServerContext context; HelloRequest request; ServerAsyncResponseWriter<HelloReply> responder; service.RequestSayHello(&context, &request, &responder, &cq, &cq, (void*)1);
Wait for the completion queue to return the tag. The context, request and
responder are ready once the tag is retrieved.
HelloReply reply; Status status; void* got_tag; bool ok = false; cq.Next(&got_tag, &ok); if (ok && got_tag == (void*)1) { // set reply and status responder.Finish(reply, status, (void*)2); }
Wait for the completion queue to return the tag. The rpc is finished when the
tag is back.
void* got_tag; bool ok = false; cq.Next(&got_tag, &ok); if (ok && got_tag == (void*)2) { // clean up }
To handle multiple rpcs, the async server creates an object CallData
to
maintain the state of each rpc and use the address of it as the unique tag. For
simplicity the server only uses one completion queue for all events, and runs a
main loop in HandleRpcs
to query the queue.
For a working example, refer to greeter_async_server.cc.