“This is the 11th day of my participation in the First Gwen Challenge 2022. Spring Web development usually uses JSON as data interaction, today we will learn a little different, using Protobuf as data interaction, and compare JSON as data interaction and Protobuf as data interaction speed and advantages and disadvantages.

Preparation before use:

  1. Create a New Maven Spring Boot project (version 2.6.3)

  2. The pom.xml configuration file adds the Protobuf compilation configuration plug-in, as well as protobuf-related Maven dependencies

    <dependencies>
        <dependency>
          <groupId>com.google.protobuf</groupId>
          <artifactId>protobuf-java</artifactId>
          <version>3.19.2</version>
        </dependency>
    </dependencies>
    
    <plugins>
          <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <version>0.6.1</version>
            <configuration>
              <protoSourceRoot>${basedir}/src/main/resources</protoSourceRoot>
              <protocArtifact>Com. Google. Protobuf: protoc: 3.19.1: exe: ${OS. Detected. Classifier}</protocArtifact>
              <pluginArtifact>IO. GRPC: protoc - gen - GRPC - Java: 1.43.1: exe: ${OS. Detected. Classifier}</pluginArtifact>
              <outputDirectory>src/main/java</outputDirectory>
              <clearOutputDirectory>false</clearOutputDirectory>
              <pluginId>grpc-java</pluginId>
            </configuration>
            <executions>
              <execution>
                <goals>
                  <goal>compile</goal>
                  <goal>compile-custom</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
        </plugins>
      </build>
    Copy the code

    1. Spring accesses Protobuf

    The principle is the same as JSON: a message converter converts the data returned by the server into the appropriate format.

    The use of Protobuf: details refer to the website (developers.google.com/protocol-bu…

    1.1 Define proto files

    The proto file is used to define Java-like beans. Let’s define an mxsm.proto file

    syntax = "proto3";
    package mxsm;
    option java_package = "com.github.mxsm.springboot.protobuf";
    option java_outer_classname = "ProtobufMessage";
    
    message Course {
        int32 id = 1;
        string course_name = 2;
        repeated Student student = 3;
    }
    message Student {
        int32 id = 1;
        string first_name = 2;
        string last_name = 3;
        string email = 4;
        repeated PhoneNumber phone = 5;
        message PhoneNumber {
            string number = 1;
            PhoneType type = 2;
        }
        enum PhoneType {
            MOBILE = 0;
            LANDLINE = 1; }}Copy the code

    1.2 Compile proto files into Java classes

    Compile to Java beans using Protobuf Maven configured earlier.

This completes the compilation, generating the ProtobufMessage class

1.3 Configuring the Spring Message Converter

@Configuration
public class Config {
    @Bean
    public ProtobufHttpMessageConverter protobufHttpMessageConverter(a) {
        return newProtobufHttpMessageConverter(); }}Copy the code

ProtobufHttpMessageConverter Spring provides support.

This completes the configuration process:

1.4 test Protobuf

@SpringBootTest(classes = SpringProtobufBootstrap.class)
public class ApplicationTest {
    // Other declarations
    private static final String COURSE1_URL = "http://localhost:8080/courses/2";


    private RestTemplate restTemplate = new RestTemplate();

    @Test
    public void whenUsingRestTemplate_thenSucceed(a) { List<HttpMessageConverter<? >> list =new ArrayList<>();
        list.add(newProtobufHttpMessageConverter()); restTemplate.setMessageConverters(list); ResponseEntity<Course> course = restTemplate.getForEntity(COURSE1_URL, Course.class); System.out.println(course.toString()); }}Copy the code

Test results:

2. Comparison of Spring JSON and Protobuf performance

Apache JMeter for testing tools of the interface.

Write the test interface first

@RestController
public class JsonProtobufController {

    @RequestMapping("/student/{id}")
    Student protobuf(@PathVariable Integer id) {
        return Student.newBuilder().setId(id).setFirstName("maxsm").setLastName("sdfsdfsdfsdfsdfsdsdfsdfsdfsdfsdfsdfsdfsdf")
            .setEmail("[email protected]").addPhone(Student.PhoneNumber.newBuilder().setNumber("12345sdfsdfsd6566666").setType(
                Student.PhoneType.MOBILE).build()).build();
    }


    @RequestMapping("/studentjson/{id}")
    StudentJson json(@PathVariable Integer id) {

        StudentJson json = new StudentJson();
        json.setId(id);
        json.setFirstName("maxsm");
        json.setLastName("sdfsdfsdfsdfsdfsd");
        json.setEmail("[email protected]");
        json.setPhoneNumber(new PhoneNumber("123456566666",PhoneType.MOBILE));

        returnjson; }}Copy the code

JSON test results:

Protobuf test results:

Protobuf is better than JSON. This is consistent with the performance of Protobuf compared to JSON in the previous article “Protobuf vs. JSON – Talking Data”.

3. Pros and cons of JSON and Protobuf

  • JSON is kind of developer-friendly, whereas Protobuf is kind of serialized time and has more space than Protobuf for the same data. This gives Protobuf an advantage over networks
  • The disadvantage of Protobuf is that you need to define a PROto file, which is the same proto file on both the receiver and sender and then compiled into the corresponding platform data structure. This increases the complexity of development. It also makes it harder to get started.

For the pros and cons of both, try to combine the pros and cons of JSON with the pros and cons of Protobuf. JSON is developer-friendly and Protobuf’s serialization footprint is small.

The code address used above: github.com/mxsm/spring…