There are times when the latest is not enough in the world. For example, IE, IE, IE. That's why I hope it will be a reference for those who have to work hard to develop in an old environment. Others have written the explanation of gRPC itself in detail, so please look for it.
Roughly this environment. Various old.
While referring to the following. https://grpc.io/docs/tutorials/basic/java/ https://github.com/grpc/grpc-java/blob/master/examples/README.md
If you can't afford it, please skip here.
Let's create an environment quickly with Docker as usual.
$ docker run --rm -it --name grpc-java -p 50051:50051 ubuntu
root@e7b3b2c13c0b:/# apt-get update
root@e7b3b2c13c0b:/# apt-get install -y git openjdk-8-jdk maven
root@e7b3b2c13c0b:/# git clone -b v1.22.1 https://github.com/grpc/grpc-java
root@e7b3b2c13c0b:/# cd grpc-java/examples
root@e7b3b2c13c0b:/grpc-java/examples# ./gradlew installDist
By the way, tools.jar
is used, so jre
is not good.
If you do it with jre, the following error will occur.
> Task :compileJava FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileJava'.
> Could not find tools.jar. Please check that /usr/lib/jvm/java-8-openjdk-amd64 contains a valid JDK installation.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 43s
At this point, the environment is ready. Below is a sample of Hello World.
/grpc-java/examples/src/main/proto/helloworld.proto /grpc-java/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java /grpc-java/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java
Let's build and run it under / grpc-java / examples
.
root@e7b3b2c13c0b:~# cd /grpc-java/examples
root@e7b3b2c13c0b:/grpc-java/examples# mvn clean compile
root@e7b3b2c13c0b:/grpc-java/examples# mvn exec:java -Dexec.mainClass=io.grpc.examples.helloworld.HelloWorldServer &
[1] 5817
root@e7b3b2c13c0b:/grpc-java/examples#
root@e7b3b2c13c0b:/grpc-java/examples# mvn exec:java -Dexec.mainClass=io.grpc.examples.helloworld.HelloWorldClient
If you see Greeting: Hello world
, you're done.
This time the server and client are running on the same terminal.
If you want to shut down the server, follow the steps below. (fg
-> Ctrl + C
)
root@e7b3b2c13c0b:/grpc-java/examples# fg
mvn exec:java -Dexec.mainClass=io.grpc.examples.helloworld.HelloWorldServer
^C*** shutting down gRPC server since JVM is shutting down
*** server shut down
root@e7b3b2c13c0b:/grpc-java/examples#
If you have modified the proto file, run ./gradlew install Dist
to generate the Java code.
If you want to change the Java execution options, you can set MAVEN_OPTS
.
MAVEN_OPTS="-server -Xmx1024m -Xms1024m -Xloggc:/grpc-java/examples/GC.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xverify:none -Djava.security.egd=file:/dev/./urandom -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+CMSClassUnloadingEnabled -XX:+DisableExplicitGC -XX:+PrintTenuringDistribution -XX:-Inline"
export MAVEN_OPTS
Well, it's finally the main subject. It is a tied-up play that prohibits the use of both Docker and Gradle on Windows. Pure gRPC is Java 7 or higher, but the sample uses Gradle and Maven 3 or higher is required (to use the plugin).
First, let's create a Maven project. The dependencies required this time are as follows. (Log is your choice)
pom.xml
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>1.22.1</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.9.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
Create a proto
folder directly under the project and create a proto file.
grpc.proto
syntax = "proto3";
option java_multiple_files = true;
option java_package = "org.mygrpc.helloworld";
option java_outer_classname = "GrpcProto";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Generate Java source from proto file. Download the file for Windows at protobuf. https://github.com/protocolbuffers/protobuf/releases/download/v3.9.0/protoc-3.9.0-win64.zip
Unzip it and place protoc.exe
under the bin
folder in the path. You can put it somewhere anew and pass it through the pass.
If you run with the full path in the future, you do not have to pass the path separately.
At the command prompt, execute the following in the folder containing grpc.proto
created earlier.
protoc --java_out=..\src\main\java grpc.proto
The source was generated under ʻorg.mygrpc.helloworld`.
.
│ pom.xml
│
├─proto
│ grpc.proto
│
└─src
├─main
│ ├─java
│ │ └─org
│ │ └─mygrpc
│ │ └─helloworld
│ │ GrpcProto.java
│ │ HelloReply.java
│ │ HelloReplyOrBuilder.java
│ │ HelloRequest.java
│ │ HelloRequestOrBuilder.java
│ │
│ └─resources
│ log4j.dtd
│ log4j.xml
│
└─test
├─java
└─resources
Actually, this is not enough. Download the tool to generate another one. https://search.maven.org/search?q=g:io.grpc%20a:protoc-gen-grpc-java
Place the downloaded exe in any folder and execute the following (change the path to the folder where the above exe is placed)
protoc --plugin=protoc-gen-grpc-java=C:\protoc\protoc-gen-grpc-java-1.22.1-windows-x86_64.exe --grpc-java_out=..\src\main\java grpc.proto
I think you have created GreeterGrpc.java
.
Create the server and client processes by referring to the sample.
HelloWorldServer.java
package org.mygrpc.helloworld;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HelloWorldServer {
/** Log. */
protected static Log log = LogFactory.getLog(HelloWorldServer.class);
private Server server;
private void start() throws IOException {
int port = 50051;
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.build()
.start();
log.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
HelloWorldServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop() {
if (server != null) {
server.shutdown();
}
}
/**
* Await termination on the main thread since the grpc library uses daemon threads.
*/
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
/**
* Main launches the server from the command line.
*/
public static void main(String[] args) throws IOException, InterruptedException {
final HelloWorldServer server = new HelloWorldServer();
server.start();
server.blockUntilShutdown();
}
static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
}
HelloWorldClient.java
package org.mygrpc.helloworld;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HelloWorldClient {
/** Log. */
protected static Log log = LogFactory.getLog(HelloWorldClient.class);
public static void main(String[] args) throws Exception {
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 50051).usePlaintext().build();
GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc
.newBlockingStub(channel);
try {
HelloRequest request = HelloRequest.newBuilder().setName("World").build();
try {
HelloReply resp = blockingStub.sayHello(request);
log.info(resp.getMessage());
} catch (StatusRuntimeException e) {
log.warn("RPC failed: " + e.getStatus());
return;
}
} finally {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
}
}
If you run the server and client respectively and output Hello World
, it's OK.
Now you can finally develop.
By the way, it seems that there are the following plug-ins for editing proto files, but I gave up because version 2.3.0 or higher requires Eclipse 4.6 Neon or higher. https://github.com/google/protobuf-dt
Recommended Posts