GRPC Create Java server side and sample client

Source: Internet
Author: User

In these days work needs to use GRPC to interact, found a lot of relevant Chinese information, said that most of them are copied from the official website, no understanding of their own reconciliation, which led me to spend almost a day of working days to figure out what's going on, here I write a simple and understandable way to record, In case you forget the day you can check.

First of all, we discard the official website of the set again to do the operation again, I was using the idea of the specific IDE this issue depending on the individual situation, the first is the same as the creation of an empty MAVEN project.


Once this empty project is created, we can configure the basic MAVEN-related configuration, where we can copy the descend network configuration.

<name>test-grpc</name> <url>http://maven.apache.org</url> <properties> <g rpc.version>1.4.0</grpc.version><!--current_grpc_version--> </properties> <dependencies&
        Gt <dependency> <groupId>io.grpc</groupId> &LT;ARTIFACTID&GT;GRPC-NETTY&LT;/ARTIFAC
            tid> <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> &LT;GROUPID&GT;IO.GRPC&L T;/groupid&gT <artifactId>grpc-testing</artifactId> <version>${grpc.version}</version> & lt;scope>test</scope> </dependency> <dependency> <groupId>junit<
            /groupid> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupid>or G.mockito</groupid> <artifactId>mockito-core</artifactId> &LT;VERSION&GT;1.9.5&L t;/version> <scope>test</scope> </dependency> </dependencies> <b uild> <extensions> <extension> <groupid>kr.motd.maven</groupid > <artifactId>os-maven-plugin</artifactId> <version>1.4.1.final</v Ersion> </extension> </extensions> <plugins> <plugin> <grou Pid>org.xolstice.maven.plugins</groupid> &LT;ARTIFACTID&GT;PROTOBUF-MAVEN-PLUGIN&LT;/ARTIFACTID&G
                T <version>0.5.0</version> <configuration> &LT;PROTOCARTIFACT&GT;COM.G Oogle.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.dete
                    Cted.classifier}</pluginartifact> </configuration> <executions> <execution> <goals> <goal>compile</go Al> <goal>compile-custom</goal> </goals>
                    </execution> </executions> </plugin> </plugi Ns> </build>

After completing the first step pom.xml configuration, you can try to package the MVN install command, and if it is correct, you will be able to get a build success message, and if that's OK, go to the next step.

We know that the core of GRPC is the definition of the network interface through Google's proto file, where we first need to create a proto file



Empty files are created under the Proto directory, and then we write to this blank proto for the required content, the specific proto file syntax is not introduced here, we choose one of the simplest form


Here's a simple explanation for these syntax is syntax, the amount we use here is the Proto3 style. If you use Proto2 style, then string cannot be used alone.

Java_package generation of Java code package

File name of JavaBean created by Java_outer_classname

Java_multiple_files If you need multiple files, and if this option is true then our testinput and Testoutput will have two separate files, In general work a proto often have many different interface definitions, so here we'll just talk about false, which is the case of file unification.

The specific method and the definition of the Bean class are no longer expanded

Then we refer to the website to the tutorial to write the server and client information, after writing a good proto mvn install will see the following file structure to create the default class


We will copy these classes to our Java code directory, and create two empty classes TestServer and testclient through these two classes to test the client and the server, where the code of servers is divided into three parts, the main method is simply skipped

public static void Main (string[] args) throws IOException, Interruptedexception {
        final testserver server = new Testse RVer ();
        Start the server
        Server.start ();
        Block server prevents
        Server.blockuntilshutdown () from being closed;
    

The next Start method is the core of the startup service.

    private void Start () throws IOException {/
    * the port on which the server should run */
        int port = 50051;
        This section starts server
        server = serverbuilder.forport (port)
                . AddService (New Testimpl ()). Build
                ()
                . Start ();

}

and the specific service implementation is accomplished by the TestFunction method of overloading Testservicegrpc

Static Class Testimpl extends Testservicegrpc.testserviceimplbase {

        //base Testserviceimplbase The underlying class implements the corresponding method
        @ Override public
        void TestFunction (testproto.testinput req, streamobserver<testproto.testoutput> Responseobserver) {
            Testproto.testoutput reply = TestProto.TestOutput.newBuilder (). Setkey ("rind" +req.getkey ()). Build ();
            Responseobserver.onnext (reply);
            Responseobserver.oncompleted ();
        }

Of course, here is to simplify, in practical applications need to use a separate class for this testservicegrpc.testserviceimplbase each of the methods in each server to overload and implement

Next we need to prepare testclient related content, the content that the Guan net obtains simplifies, discovers the entire logic or is relatively simple divides into two methods the Main method skips the explanation

public static void Main (string[] args) throws Exception {
        testclient client = new TestClient ();
        try {
            String user = "Big sima";
            Call the corresponding method
            client.test (user);
        } finally {
        }
}

The test method that is called is basically initializing and connecting to the Send request

public void Test (String name) {
        Testproto.testinput request = TestProto.TestInput.newBuilder (). Setkey (name). Build ();
        Testproto.testoutput response;
        try {
            Channel Channel =  managedchannelbuilder.foraddress ("localhost", 50051). Useplaintext (True). Build ();
            Testservicegrpc.testserviceblockingstub blockingstub =testservicegrpc.newblockingstub (channel);
            Call method
            response = blockingstub.testfunction (request);
        } catch (Statusruntimeexception e) {return
            ;
        }
        logger.info ("greeting:" + response.getkey ());
}

Results that were eventually printed on the client







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.