JAVA:Spring Boot 集成 Protobuf 数据系列化协议

admin
6
2025-10-22

🚀 1、简述

在分布式服务通信中,数据序列化与反序列化的效率对系统性能影响极大。Protocol Buffers(Protobuf) 是由 Google 提出的一种高效的结构化数据序列化协议,具有:

🔹🔥 高性能(远优于 JSON/XML)

🔹📦 跨语言支持

🔹📉 较小的体积

本篇将带你了解如何在 Spring Boot 中集成 Protobuf 并进行实践应用。

image-jnyp.png


📌 2、为什么选用 Protobuf?

对比项 JSON XML Protobuf
可读性 低(需工具)
序列化效率
数据体积 更大
跨语言支持 良好 良好 非常好

样例代码:https://gitee.com/lhdxhl/springboot-example.git

适合:微服务间通信、消息中间件、IoT 设备、移动端传输。


⚙️ 3、实践样例

3.1 添加 Maven 依赖

<dependencies>
    <!-- Protobuf Java 支持 -->
    <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java</artifactId>
        <version>3.25.1</version>
    </dependency>

    <!-- Spring Boot Protobuf 支持 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <extensions>
        <!-- 让 protobuf 插件生效 -->
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.7.0</version>
        </extension>
    </extensions>

    <plugins>
        <!-- protobuf 插件 -->
        <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <version>0.6.1</version>
            <configuration>
                <protocArtifact>com.google.protobuf:protoc:3.25.1:exe:${os.detected.classifier}</protocArtifact>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

3.2 编写 .proto 文件

创建文件 src/main/proto/user.proto

syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.example.protobuf.model";
option java_outer_classname = "UserProto";

message User {
  int32 id = 1;
  string name = 2;
  string email = 3;
}

🛠️ 编译 Proto 文件

运行:

mvn compile

生成的 Java 类位于:

target/generated-sources/protobuf/java/com/example/protobuf/model/User.java

3.3 控制器接口

package com.lm.protobuf.controller;

import com.lm.protobuf.model.User;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping(value = "/{id}", produces = "application/x-protobuf")
    public User getUser(@PathVariable int id) {
        return User.newBuilder()
                .setId(id)
                .setName("张三")
                .setEmail("zhangsan@example.com")
                .build();
    }

    @PostMapping(consumes = "application/x-protobuf", produces = "application/x-protobuf")
    public User createUser(@RequestBody User user) {
        System.out.println("接收到用户:" + user.getName());
        return user;
    }
}


📬 4、测试与调用

4.1 使用 curl 测试 Protobuf 接口

curl -H "Accept: application/x-protobuf" http://localhost:8080/user/1 --output user.bin

4.2 使用 Java 客户端调用

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("application", "x-protobuf"));

User user = User.newBuilder()
        .setId(100)
        .setName("李四")
        .setEmail("lisi@example.com")
        .build();

HttpEntity<UserProto.User> entity = new HttpEntity<>(user, headers);

ResponseEntity<UserProto.User> response = restTemplate.postForEntity(
        "http://localhost:8080/user", entity, UserProto.User.class);

System.out.println(response.getBody());

🧠 5、总结

Spring Boot 集成 Protobuf 非常适合对传输效率有较高要求的系统。通过 .proto 结构定义数据模型后,自动生成代码,配合 @RestController 实现高效、紧凑的 HTTP 接口。

场景 说明
微服务通信 用于服务间高性能数据交换,代替 JSON
数据序列化传输 用于缓存、Kafka、RocketMQ 等消息中间件
移动端通信 Android/iOS 使用 Proto 与服务器通信
配合 gRPC 使用 Spring Boot + gRPC 的服务定义方式
边缘计算/IoT 场景 网络带宽受限时传输结构化二进制数据

优点:

🔹💨 比 JSON 更快、更省带宽

🔹🧱 可拓展且结构清晰

🔹🌍 支持跨语言调用(Python、Go、C++)

image.png

动物装饰