New projects need to use google protobuf to generate java code
The first step is to start. Many tutorials on the Internet say to download the protobuf support plug-in, but I have downloaded many idea versions, but I can’t find the protobuf support plug-in .
Select file ->settings ->plugin in idea and search for protobuf. Generally, there are the following options:
Here, I choose to download
protobuf generate, -------- generated plug-in
protobuf highlighted、--------syntax highlighting
Protocol Buffers ----------Syntax support
I blindly guessed that protobuf support is an integration of the above plug-ins. Since I couldn't find it, I never tried using protobuf support . But to generate code, the above three plug-ins are enough.
Step 2: After the above plug-in is installed and restarted, create a new maven project, open IDEA, select "New Project", select Maven, select the Java version, then fill in the project information to create a new Maven project.
The third step is to introduce the following dependencies in the pom.xml file:
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.34.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.34.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.34.1</version>
</dependency>
These dependencies will help us introduce gRPC and protobuf libraries.
The fourth step is to write the .proto file
Create a file named helloworld.proto in the src/main/proto directory of the project with the following content:
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.example.grpc";
option java_outer_classname = "HelloWorldProto";
package helloworld;
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
service HelloService {
rpc sayHello(HelloRequest) returns (HelloResponse);
}
This file defines a HelloWorld service and two request and response messages.
Step 5: Download the protoc.exe compiler
Download address: Releases · protocolbuffers/protobuf · GitHub
After downloading, unzip it and configure the environment variable: PROTOCBUF_HOME
Then under the PATH of the system variable, add: %PROTOCBUF_HOME%\bin
Then open the command prompt: enter protoc,
The above prompt pops up, indicating success.
Step 6: Generate java code
idea -> tools–>configure genprotobuf
a). Configure protoc path (specify the protoc executable file path after decompression in step 5),
b). Quick Gen: select java
c). Output path: check java and specify protoc The path where the generated java file needs to be stored
Start generating java client files
Click: tools–>Generate all Protobufs
The following code was successfully generated: