DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • A Spring Boot App With Half the Startup Time
  • Improving Java Application Reliability with Dynatrace AI Engine
  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus

Trending

  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing
  • Solving Comprehension Debt in AI-Generated Codebases
  • Avoiding AI Debt as a Team
  • YAGNI in the Age of AI Coding

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Add gRPC to Your Java Application

Add gRPC to Your Java Application

Learn how to autogenerate gRPC code, back a gRPC service with implementation, and spin up a server to send a response to a client.

By 
Emmanouil Gkatziouras
DZone Core CORE ·
Nov. 05, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

gRPC is a high-performance, open-source universal RPC framework.
There are various benefits to using gRPC.

  • It simplifies development by providing client/server code.
  • It supports multiple languages.

It all starts with defining a .proto file, .proto files reside on src/main/proto file.

Be aware it is a good practice to keep proto files on a repo and have some schema versioning. This way developers from other teams could generate their SDKs by referencing them, even for other languages.

We shall create an Order Service on src/main/proto/Order.proto:

Go
 
syntax = "proto3";
 
option java_multiple_files = true;
option java_package = "com.egkatzioura.order.v1";
 
service OrderService {
    rpc ExecuteOrder(OrderRequest) returns (OrderResponse) {};
}
 
message OrderRequest {
    string email = 1;
    string product = 2;
    int32 amount = 3;
}
 
message OrderResponse {
    string info = 1;
}


In order to work with gRPC the following binaries need to be placed:

XML
 
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty-shaded</artifactId>
    <version>1.39.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-protobuf</artifactId>
    <version>1.39.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-stub</artifactId>
    <version>1.39.0</version>
</dependency>
<dependency> <!-- necessary for Java 9+ -->
    <groupId>org.apache.tomcat</groupId>
    <artifactId>annotations-api</artifactId>
    <version>6.0.53</version>
    <scope>provided</scope>
</dependency>


XML
 
<build>
    <extensions>
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.6.2</version>
        </extension>
    </extensions>
    <plugins>
        <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <version>0.6.1</version>
            <configuration>
                <protocArtifact>com.google.protobuf:protoc:3.17.2:exe:${os.detected.classifier}</protocArtifact>
                <pluginId>grpc-java</pluginId>
                <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.39.0:exe:${os.detected.classifier}</pluginArtifact>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


By executing mvn clean install, the classes will be generated on target/classes.
Those classes are more than enough to spin up a server and run a client to communicate to it.

Therefore let’s try to spin up the server.

We shall create a service Implementation:

 
package com.egkatzioura.order.impl;
 
import com.egkatzioura.order.v1.Order;
import com.egkatzioura.order.v1.OrderServiceGrpc;
 
import io.grpc.stub.StreamObserver;
 
public class OrderServiceImpl extends OrderServiceGrpc.OrderServiceImplBase {
 
    @Override
    public void executeOrder(Order.OrderRequest request, StreamObserver<Order.OrderResponse> responseObserver) {
 
        Order.OrderResponse response = Order.OrderResponse.newBuilder()
                                                          .setInfo("Hi "+request.getEmail()+", you order has been executed")
                                                          .build();
 
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}


Then our main class will spin up the server and serve the request.

Java
 
package com.egkatzioura.order;
 
import java.io.IOException;
 
import com.egkatzioura.order.impl.OrderServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
 
public class Application {
 
    public static void main(String[] args) throws IOException, InterruptedException {
        Server server = ServerBuilder
                .forPort(8080)
                .addService(new OrderServiceImpl()).build();
 
        server.start();
        server.awaitTermination();
    }
 
}


While the server is running we can spin up another main class which shall communicate to the server and execute a gRPC request towards the server.

Java
 
package com.egkatzioura.order;
 
import com.egkatzioura.order.v1.Order;
import com.egkatzioura.order.v1.OrderServiceGrpc;
 
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
 
public class ApplicationClient {
    public static void main(String[] args) {
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 8080)
                                                      .usePlaintext()
                                                      .build();
 
        OrderServiceGrpc.OrderServiceBlockingStub orderServiceBlockingStub
                = OrderServiceGrpc.newBlockingStub(managedChannel);
 
        Order.OrderRequest orderRequest = Order.OrderRequest.newBuilder()
                                             .setEmail("[email protected]")
                                             .setProduct("no-name")
                                             .setAmount(3)
                                             .build();
 
        Order.OrderResponse orderResponse = orderServiceBlockingStub.executeOrder(orderRequest);
 
        System.out.println("Received response: "+orderResponse.getInfo());
 
        managedChannel.shutdown();
    }
}


So we just autogenerated gRPC code, we backed a gRPC service with an implementation, a server spun up and a client got a response from the server.

You can find the source code on Github.

On the next blog, we shall add gRPC to our Spring Application.

application Java (programming language)

Published at DZone with permission of Emmanouil Gkatziouras. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Spring Boot App With Half the Startup Time
  • Improving Java Application Reliability with Dynatrace AI Engine
  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook