📅  最后修改于: 2023-12-03 14:45:40.555000             🧑  作者: Mango
Protobuf (Protocol Buffers) is a language-agnostic binary serialization format used by Google to serialize structured data for communication between their internal services. It is an efficient way to communicate over a network, and is much faster than XML or JSON. It provides a simple and flexible interface for serializing structured data.
Gradle is a powerful build automation tool that allows you to automate your build process. It is designed to be flexible and easy to use, and has a wide range of plugins to help you streamline your development workflow.
In this tutorial, we will walk through how to use Protobuf with Java and Gradle.
To follow this tutorial, you will need:
You can download the latest JDK from the Oracle website and the latest version of Gradle from the Gradle website.
First, let's create a Gradle project for our Java application. Open a terminal window and navigate to the directory where you want to create your project.
$ mkdir protobuf-java-gradle
$ cd protobuf-java-gradle
Create a new Gradle project using the init
command:
$ gradle init
This will create a new Gradle project with the following directory structure:
protobuf-java-gradle/
├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
Next, let's add the Protobuf plugin to our build.gradle
file. This will allow us to compile our .proto
files into Java code.
Open the build.gradle
file in your favorite text editor and add the following lines:
plugins {
id 'java'
id "com.google.protobuf" version "0.8.17"
}
group 'com.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.protobuf:protobuf-java:3.17.3'
testCompile group: 'junit', name: 'junit', version: '4.12'
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.17.3'
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.39.0'
}
}
generateProtoTasks {
all().each { task ->
task.plugins {
grpc {}
}
}
}
}
Let's break down what each of these lines does:
plugins
: This section adds the Java and Protobuf plugins to our project. The com.google.protobuf
plugin allows us to compile our Protobuf files into Java code.group
and version
: These settings are used to identify our project when we publish it.repositories
: This section tells Gradle where to find the dependencies for our project. We are using the default Maven Central repository.dependencies
: This section specifies the dependencies for our project. We are adding the Protobuf library and the JUnit testing library.protobuf
: This section configures the Protobuf plugin. We specify the version of the protoc
compiler we want to use, as well as the version of the protoc-gen-grpc-java
plugin for generating gRPC code. We also tell the plugin to generate gRPC code for all .proto
files.Now that we have our Gradle project set up with the Protobuf plugin, let's create a .proto
file. This file will define the structure of the data we want to serialize.
Create a new file called person.proto
in the src/main/proto
directory with the following contents:
syntax = "proto3";
package com.example;
message Person {
string name = 1;
int32 id = 2;
repeated string email = 3;
}
This file defines a Person
message with three fields: name
, id
, and email
.
Now that we have our .proto
file, we can generate Java code from it using the protobuf
Gradle task.
In a terminal window, run the following command in the root directory of your project:
$ ./gradlew generateProto
This will generate Java code from your .proto
files and place it in the build/generated/source/proto/main/java
directory.
Now that we have generated Java code from our .proto
file, let's use it in our Java code.
Create a new App.java
file in the src/main/java
directory with the following contents:
package com.example;
import java.io.IOException;
public class App {
public static void main(String[] args) throws IOException {
Person person = Person.newBuilder()
.setName("John Doe")
.setId(123)
.addEmail("johndoe@example.com")
.addEmail("johndoe@gmail.com")
.build();
byte[] data = person.toByteArray();
System.out.printf("Serialized data length: %d\n", data.length);
Person parsedPerson = Person.parseFrom(data);
System.out.printf("Parsed person: %s\n", parsedPerson.toString());
}
}
This code serializes a Person
object to a byte array using the toByteArray()
method, and then deserializes it back into a Person
object using the parseFrom()
method.
Now that we have our Protobuf and Java code written, let's build and run the application.
In a terminal window, run the following command in the root directory of your project:
$ ./gradlew build
This will build your application and create a JAR file in the build/libs
directory.
Run the application with the following command:
$ java -jar build/libs/protobuf-java-gradle-1.0-SNAPSHOT.jar
This will serialize a Person
object to a byte array, deserialize it back into a Person
object, and print the results to the console.
In this tutorial, we walked through how to use the Protobuf plugin with Java and Gradle to serialize and deserialize structured data. By using Protobuf, you can easily communicate between services in a fast and efficient manner.