Google multi-language communication framework Grpc

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Google multi-language communication Framework GRPC Series (i) overview

GRPC Overview

3/26/2016 9:16:08 AM

Directory

I. Overview

Second, compiling GRPC

Third, use GRPC in C #

Iv. using GRPC in C + +

has been looking for multi-platform multi-lingual communication framework, Microsoft's WCF framework is very powerful and flexible, although it can also through the custom binding and other technology client communication, but has not implemented a multi-platform technical framework of unity. Google's grpc is a good choice, and Google's solutions are more mature and generic than similar frameworks thrift. Insufficient is due to just open source, the use of limited scope, less domestic information. Just compiling C + + GRPC, for example, took me two days. In this series, I'll show you the details of using GRPC in each language.

GRPC is an open source communication framework at the beginning of google2015.

With GRPC, you can invoke the server-side approach on different machines at the client side, and the development language and operating environment of the client and server can be many, covering the mainstream language and platform. The protocols that interact with each other can be defined in the proto file, and the client and server can easily generate protocols and proxy code through the tool. And the message encoding is adopted google protocol buffer , the data volume is small, the speed is fast.

is a simple grpc use scenario, the server is developed in C + +, the client can be anroid, and Ruby.

GRPC has the following characteristics:

    • Based on HTTP/2, the mechanism of connection multiplexing, Body and Header compression is provided. It can save bandwidth, reduce the number of TCP links, save CPU usage and prolong battery life.
    • Support for mainstream development languages (C, C + +, Python, PHP, Ruby, NodeJS, C #, Objective-c, Golang, Java)
    • The IDL (Interface Definition Language) layer uses the Protocol buffers, which is ideal for team interface design

Here are examples of C #, C + +, Java client and server, which pass a name to the server and return a string to the server XXX hello XXX .

Proto file as a communication protocol

The same proto file is used regardless of the language in which the client and the server are created. The proto file defines the protocol interface and data format. Different languages follow the proto file to generate the server interface and service class, the client's service proxy, but the command to generate the tool is different.
The proto file is as follows:

Syntax ="Proto3";Option Java_multiple_files =true; option java_package =  "Io.grpc.examples.helloworld"; option java_outer_classname =  "Helloworldproto"; option objc_class_prefix = " HLW ";p ackage 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 Greetingsmessage helloreply {string message = 1;}   

C # service side and client code

The client proxy for C # is generated by the tool, so it's simple.

Client

public static void Main(string[] args){ Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = Greeter.NewClient(channel); String user = "paul"; var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + reply.Message); channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey();}

Service side

Class greeterimpl:greeter.igreeter{Server side handler of the SayHello RPCPublic taskReturn Task.fromresult (New Helloreply {Message ="Hello" + request. Name}); }}Class program{const int Port = 50051; public static  void main (string[] args) {Server Server = new server {Services = {Greeter.bindservice (new Greeterimpl ())}, Ports = {new serverport ( "localhost", Port, servercredentials.insecure)}}; Server. Start (); Console.WriteLine ( "Greeter Server listening on port" + port); Console.WriteLine ( "Press any key to stop the server ..."); Console.readkey (); Server. Shutdownasync (). Wait (); }}

Server and client code for C + +

The Client Agent for C + + cannot be generated by the tool and needs to be written manually.

C + + ClientClass Greeterclient {Public:greeterclient (std::shared_ptr<channel> Channel): Stub_ (Greeter::newstub (channel)) {}Assambles the client ' s payload, sends it and presents the response backFrom the server. STD::String SayHello (CONST STD::string& user) {Data we is sending to the server. Hellorequest request; Request.set_name (user);Container for the data we expect from the server. helloreply reply;Context for the client. It could is used to convey extra information toThe server and/or tweak certain RPC behaviors. ClientContext context;The actual RPC. Status status = Stub_->sayhello (&context, request, &reply);ACT upon its status.if (Status.ok ()) {return Reply.message (); }else {Return"RPC failed"; } }Private:std::unique_ptr<greeter::stub> stub_;}; int main (int argc, char** argv) {Instantiate the client. It requires a channel, out of which the actual RPCsis created. This channel models a connection to an endpointlocalhost at Port 50051). We indicate that the channel isn ' t authenticated(Use of Insecurechannelcredentials ()). Greeterclient greeter (Grpc::createchannel ("localhost:50051", Grpc::insecurechannelcredentials ())); STD::String User ("World"); STD::string reply = Greeter. SayHello (user); Std::cout <<"Greeter Received:" << reply << Std::endl;Return0;}C + + Service sideLogic and data behind the server ' s behavior.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; }};void Runserver () {std::String Server_address ("0.0.0.0:50051"); Greeterserviceimpl Service; Serverbuilder Builder;Listen on the given address without any authentication mechanism. Builder. Addlisteningport (Server_address, Grpc::insecureservercredentials ());//Register "service" as the instance through which we ' ll communicate with //clients. In the IT corresponds to an *synchronous* service. Builder. Registerservice (&service); //Finally assemble the server. Std::unique_ptr<server> server (builder. Buildandstart ()); Std::cout << "Server listening on" << server_address << Std::endl; //Wait for the server to shutdown. Note that some and other thread must is//responsible for shutting, the server for this, the call to ever return. server-& Gt Wait ();} int main (int argc, char** argv) {runserver (); return 0;}       

Server and client code for Java

The Java language is not natively supported by GRPC, but the GRPC is implemented using Java, which is the framework gRPC-java . gRPC-javayou can interact with the GRPC client and server side as well.

Java Client code:
Like C + +, Java clients still cannot automatically generate service proxy classes directly, and need to be created manually.

Package Io.grpc.examples.helloworld;Import Io.grpc.ManagedChannel;Import Io.grpc.ManagedChannelBuilder;Import io.grpc.StatusRuntimeException;Import Java.util.concurrent.TimeUnit;Import Java.util.logging.Level;Import Java.util.logging.Logger;/** * A simple client this requests A greeting from the {@link Helloworldserver}. */PublicClasshelloworldclient {PrivateStaticFinal Logger Logger = Logger.getlogger (HelloWorldClient.class.getName ());PrivateFinal Managedchannel channel;PrivateFinal Greetergrpc.greeterblockingstub blockingstub;/** Construct Client connecting to HelloWorld server at {@code Host:port}. */PublicHelloworldclient(String host,int port) {channel = Managedchannelbuilder.foraddress (host, Port). Useplaintext (true). Build (); Blockingstub = Greetergrpc.newblockingstub (channel); }PublicvoidShutdown()Throws Interruptedexception {Channel.shutdown (). Awaittermination (5, Timeunit.seconds); }/** Say hello to server. */PublicvoidGreet(String name) {Logger.info ("Would try to greet" + name +" ..."); Hellorequest request = Hellorequest.newbuilder (). SetName (name). build (); Helloreply response;try {response = Blockingstub.sayhello (request);}catch (Statusruntimeexception e) {Logger.log (level.warning,"RPC failed: {0}", E.getstatus ());Return } logger.info ("Greeting:" + response.getmessage ());}/** * Greet server. If provided, the first element of {@code args} is the name of the greeting. */public static void main (string[] args) throws Exception {helloworldclient client = new Helloworldclient ( "localhost", 50051); try {/* Access a service running on the local machine on port 50051 */String user =  "world"; if (Args.length > 0) {user = Args[ 0]; /* use the ARG as the name to greet if provided */} client.greet (user); } finally {Client.shutdown ();}}}         

Java Service-side code:

Package Io.grpc.examples.helloworld;Import Io.grpc.Server;Import Io.grpc.ServerBuilder;Import Io.grpc.stub.StreamObserver;Import java.io.IOException;Import Java.util.logging.Logger;/** * Server that manages startup/shutdown of a {@code Greeter} server. */PublicClassHelloworldserver {PrivateStaticFinal Logger Logger = Logger.getlogger (HelloWorldServer.class.getName ());/* The port on which the server should run */Privateint port =50051;Private server server;PrivatevoidStart()Throws IOException {server = Serverbuilder.forport (port). AddService (Greetergrpc.bindservice (New Greeterimpl ()). Build (). Start (); Logger.info ("Server started, listening on" + port); Runtime.getruntime (). Addshutdownhook (New Thread () {@OverridePublicvoidRun() {Use stderr here since the logger, and the been reset by its JVM shutdown hook. System.err.println ("* * * * shutting down GRPC server since JVM was shutting down"); Helloworldserver.This.stop (); System.err.println ("* * * server shut down"); } }); }PrivatevoidStop() {if (Server! =NULL) {Server.shutdown ();}}/** * Await termination on the main thread since the GRPC library uses daemon threads. */PrivatevoidBlockuntilshutdown()Throws Interruptedexception {if (Server! =NULL) {server.awaittermination ();}}/** * Main launches the server from the command line. */PublicStaticvoidMain(string[] args)Throws IOException, Interruptedexception {final helloworldserver server = new helloworldserver (); Server.start (); Server.blockuntilshutdown (); } private class greeterimpl implements GreeterGrpc. greeter { @Override public void sayhello (Hellorequest req, streamobserver "Hello" + req.getname ()). build (); Responseobserver.onnext (reply); Responseobserver.oncompleted (); } }}
   Tags:  communication framework,  cross-platform,  grpc, proto, protocol Buffer, google

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.