Java Development GRPC Services and clients

Source: Internet
Author: User

I. Introduction of GRPC

GRPC is the GO implementation: a high-performance, open source, moving and HTTP/2 in the first generic RPC framework. Using GRPC, you can invoke methods on the client side of the server on different machines, while the client and server development languages and

The operating environment can be a variety of, basically 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 is encoded

google protocol buffer, the data volume is small, the speed is fast.

GRPC has the following characteristics:

(1) based on HTTP/2, and then provides the connection multiplexing, Body and Header compression mechanism. It can save bandwidth, reduce the number of TCP links, save CPU usage and prolong battery life.

(2) Support for mainstream development languages (C, C + +, Python, PHP, Ruby, NodeJS, C #, Objective-c, Golang, Java)

(3) IDL (Interface Definition Language) layer uses Protocol buffers, ideal for team interface design

Let's look at a Java example to see how to use Grpc.

Second, configure the Pom file, import grpc dependencies and plugins

After the new project is created, we can first configure the underlying MAVEN-related configuration, where we can copy the configuration of the Xia Guan Network:

<properties>
<grpc.version>1.4.0</grpc.version><!--Current_grpc_version--
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-testing</artifactId>
<version>${grpc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.4.1.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginartifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</ Pluginartifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

Third, write the proto file, and compile the corresponding Java file

For simplicity, the Helloworld.proto file is directly used here, and the contents are 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";

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;
}

Note here: If the client and server use different languages, such as the client using Java, the server is C + +, be sure to keep the proto file exactly the same.

After we see the website to the tutorial to write the service side and client information situation, after writing good proto after the MVN install will be in the target folder in the corresponding directory to create the default class

At this point, we just need to copy these classes into our Java code directory and develop the server and client.

Iv. development of the service side

The service-side code is as follows, and the main method of running this class can start the service on port 50051.

public class Helloworldserver {

private static final Logger Logger = Logger.getlogger (HelloWorldServer.class.getName ());


private int port = 50051;
Private server server;

private void Start () throws ioexception{
Server = Serverbuilder.forport (port)
. AddService (New Greeterimpl ())
. Build ()
. Start ();
Logger.info ("Server started, listening on" + port);

Runtime.getruntime (). Addshutdownhook (New Thread () {

@Override
public void Run () {

SYSTEM.ERR.PRINTLN ("* * * shutting down GRPC server since JVM was shutting down");
HelloWorldServer.this.stop ();
SYSTEM.ERR.PRINTLN ("* * * server shut down");
}
});
}

private void Stop () {
if (server! = null) {
Server.shutdown ();
}
}

Block until you exit the program
private void Blockuntilshutdown () throws Interruptedexception {
if (server! = null) {
Server.awaittermination ();
}
}


public static void Main (string[] args) throws IOException, Interruptedexception {

Final Helloworldserver server = new Helloworldserver ();
Server.start ();
Server.blockuntilshutdown ();
}


Implementation defines a class that implements the service interface
Private class Greeterimpl extends Greetergrpc.abstractgreeter {

@Override
public void SayHello (Hellorequest req,streamobserverhelloreply reply = Helloreply.newbuilder (). Setmessage (("Hello" +req.getname ()). build ();
Responseobserver.onnext (reply);
Responseobserver.oncompleted ();
}
}
}

V. Client Development

public class Helloworldclient {

Private final Managedchannel channel;
Private final greetergrpc.greeterblockingstub blockingstub;
private static final Logger Logger = Logger.getlogger (HelloWorldClient.class.getName ());

Public Helloworldclient (String host,int port) {
Channel = Managedchannelbuilder.foraddress (Host,port)
. Useplaintext (True)
. build ();

Blockingstub = Greetergrpc.newblockingstub (channel);
}


    public void shutdown () throws interruptedexception { 
         Channel.shutdown (). Awaittermination (5, timeunit.seconds);  
   }

    public  void greet (String 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 ());  
   }

public static void Main (string[] args) throws Interruptedexception {
Helloworldclient client = new Helloworldclient ("127.0.0.1", 50051);
try{
String user = "World";
if (Args.length > 0) {
user = Args[0];
}
Client.greet (user);
}finally {
Client.shutdown ();
}
}
}

Java Development GRPC Services and clients

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.