Try gRPC with Java, Maven

Overview

Experience gRPC! It is a memorandum such as adjustment of the build location.

environment

pom.xml settings

[pom.xml]


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com</groupId>
  <artifactId>grpc.demo2</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>grpc.demo2</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <dependencies>
		<!-- https://mvnrepository.com/artifact/io.grpc/grpc-protobuf -->
		<dependency>
		    <groupId>io.grpc</groupId>
		    <artifactId>grpc-protobuf</artifactId>
		    <version>1.22.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/io.grpc/grpc-netty -->
		<dependency>
		    <groupId>io.grpc</groupId>
		    <artifactId>grpc-netty</artifactId>
		    <version>1.22.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/io.grpc/grpc-stub -->
		<dependency>
		    <groupId>io.grpc</groupId>
		    <artifactId>grpc-stub</artifactId>
		    <version>1.22.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
		<dependency>
		    <groupId>com.google.protobuf</groupId>
		    <artifactId>protobuf-java</artifactId>
		    <version>3.9.0</version>
		</dependency>
        <!--Because it is out of the standard library from Java 9-->
		<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
		<dependency>
		    <groupId>javax.annotation</groupId>
		    <artifactId>javax.annotation-api</artifactId>
		    <version>1.3.2</version>
		</dependency>
  </dependencies>
 
  <build>
    <defaultGoal>clean generate-sources compile install</defaultGoal>
	<plugins>
		<plugin>
			<groupId>com.github.os72</groupId>
			<artifactId>protoc-jar-maven-plugin</artifactId>
			<version>3.8.0</version>
			<executions>
				<execution>
					<phase>generate-sources</phase>
					<goals>
						<goal>run</goal>
					</goals>
					<configuration>
						<includeMavenTypes>direct</includeMavenTypes>
						
						<inputDirectories>
							<include>src/main/resources</include>
						</inputDirectories>
						
						<outputTargets>
							<outputTarget>
								<type>java</type>
								<outputDirectory>src/main/java</outputDirectory>
							</outputTarget>
							<outputTarget>
								<type>grpc-java</type>
								<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.22.1</pluginArtifact>
								<outputDirectory>src/main/java</outputDirectory>
							</outputTarget>
						</outputTargets>
					</configuration>
				</execution>
			</executions>
		</plugin>	
	</plugins>
  </build>
</project>

proto file creation

Create a resources folder under src / main and create a prototype file.

[helloworld.proto]


syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.example.helloworld";

package helloworld;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

Build!

You should now have the io.grpc.example.helloworld package and source specified above.

Operation check

Now let's implement the server and client and see how it works.

[Server.java]


public class Server {

	public static void main(String[] args) throws Exception {

		int port = 8080;

		io.grpc.Server server = ServerBuilder.forPort(port).addService((BindableService) new GreeterImpl()).build();

		server.start();
		server.awaitTermination();
	}
}

[GreeterImpl.java]


public class GreeterImpl extends GreeterGrpc.GreeterImplBase {

	public void sayHello(HelloRequest reqest, StreamObserver<HelloReply> responseObserver) {

		HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + reqest.getName()).build();

		responseObserver.onNext(reply);
		responseObserver.onCompleted();
	}
}

[Client.java]


public class Client {
	public static void main(String[] args) {

		String name = "Takeshi";
		int port = 8080;

		ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build();

		GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);

		HelloRequest request = HelloRequest.newBuilder().setName(name).build();
		HelloReply reply = stub.sayHello(request);

		System.out.println("Reply: " + reply.getMessage());
	}
}

Execute Client after starting Server.

Reply: Hello Takeshi

Takeshi is back safely.

reference

GRPC Project Setup in Java Points for introducing gRPC in Java

Recommended Posts

Try gRPC with Java, Maven
Try bidirectional communication with gRPC Java
Try using Redis with Java (jar)
Develop gRPC on Windows + Java 7 + Maven 2
Try using Maven
java, maven memo
Try Java 8 Stream
Let's try WebSocket with Java and javascript!
CICS-Run Java applications-(2) Build management with Maven
Try managing Java libraries with AWS CodeArtifact
Roughly try Java 9
Try using the Wii remote with Java
[CircleCI 2.0] [Java] [Maven] [JUnit] Aggregate JUnit test results with CircleCI 2.0
Java automated test implementation with JUnit 5 + Apache Maven
Try to link Ruby and Java with Dapr
Automate Java (Maven) project build with CircleCI + Orbs
Java Repository of Eclipse with Maven: Missing artifact ~
Try to implement TCP / IP + NIO with JAVA
Try communication using gRPC on Android + Java server
Try debugging a Java program with VS Code
Try DI with Micronaut
Install java with Homebrew
Try create with Trailblazer
Change seats with java
Install Java with Ansible
Try WebSocket with jooby
Comfortable download with JAVA
Switch java with direnv
Try WildFly with Docker
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
Try Java return value
Endian conversion with JAVA
Compile with Java 6 and test with Java 11 while running Maven on Java 8
Try connecting to AzureCosmosDB Emulator for Docker with Java
Try building Java into a native module with GraalVM
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Try using RocksDB in Java
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Let's experiment with Java inlining
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
[Java] JSON communication with jackson
Try using GloVe with Deeplearning4j
Java to play with Function
Try using view_component with rails
Try scraping using java [Notes]
Try calling JavaScript in Java
Try functional type in Java! ①
Enable Java EE with NetBeans 9
[Java] JavaConfig with Static InnerClass
[Beginner] Try to make a simple RPG game with Java ①
Let's operate Excel with Java! !!
Version control Java with SDKMAN