SpringBoot使用protobuf格式的接口方式
作者:天涯屐痕 时间:2022-02-14 14:20:17
SpringBoot使用protobuf格式的接口
建立SpringBoot项目,pom.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.protobuf</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.11.0</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
<version>3.11.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.protobuf-java-format</groupId>
<artifactId>protobuf-java-format</artifactId>
<version>1.2</version>
</dependency>
<!-- 网络请求依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
编写.proto文件,内容如下:
user_login.proto:
syntax = "proto3";
option java_package = "com.boomsecret.protobuf";
option java_outer_classname = "MessageUserLogin";
message MessageUserLoginRequest {
string username = 1;
string password = 2;
}
message MessageUserLoginResponse {
string access_token = 1;
string username = 2;
}
生成java代码:
protoc.exe --java_out=./ user_login.proto
将生成的代码移动到你的项目中合适位置:
编写protobuf格式的Controller接口:
package com.example.protobuf.demo.controller;
import com.boomsecret.protobuf.MessageUserLogin;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.HttpUtils;
import java.net.URI;
import java.util.UUID;
@Controller
public class TestController {
@RequestMapping(value = "/demo/test", produces = "application/x-protobuf")
@ResponseBody
public MessageUserLogin.MessageUserLoginResponse getPersonProto(@RequestBody MessageUserLogin.MessageUserLoginRequest request) {
MessageUserLogin.MessageUserLoginResponse.Builder builder = MessageUserLogin.MessageUserLoginResponse.newBuilder();
builder.setAccessToken(UUID.randomUUID().toString()+"_res");
builder.setUsername(request.getUsername()+"_res");
return builder.build();
}
}
编写测试类,通过HttpClient工具调用接口:
package com.example.protobuf.demo;
import com.boomsecret.protobuf.MessageUserLogin;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import util.HttpUtils;
import java.net.URI;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
@Test
public void test() {
try {
URI uri = new URI("http", null, "127.0.0.1", 8080, "/demo/test", "", null);
HttpPost request = new HttpPost(uri);
MessageUserLogin.MessageUserLoginRequest.Builder builder = MessageUserLogin.MessageUserLoginRequest.newBuilder();
builder.setUsername("tom");
builder.setPassword("123456");
HttpResponse response = HttpUtils.doPost(request, builder.build());
MessageUserLogin.MessageUserLoginResponse messageUserLoginResponse = MessageUserLogin.MessageUserLoginResponse.parseFrom(response.getEntity().getContent());
System.err.println(messageUserLoginResponse.getAccessToken());
} catch (Exception e) {
}
}
}
HttpUtils内容如下:
package util;
import com.google.protobuf.GeneratedMessageV3;
import com.googlecode.protobuf.format.JsonFormat;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.HttpClients;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
* @author wangjinliang on 2018/10/18.
*/
public class HttpUtils {
public static HttpResponse doPost(HttpPost post, GeneratedMessageV3 message) throws IOException {
HttpClient httpclient = HttpClients.createDefault();
String requestUrl = post.getURI().toString();
ByteArrayInputStream inputStream = new ByteArrayInputStream(message.toByteArray());
InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream);
post.setEntity(inputStreamEntity);
post.addHeader("Content-Type", "application/x-protobuf");
for (Header header : post.getAllHeaders()) {
System.out.println(header.getName() + ":" + header.getValue());
}
StringBuilder sb = new StringBuilder();
sb.append("curl -XPOST ");
for (Header header : post.getAllHeaders()) {
sb.append(" -H \"").append(header.getName()).append(":").append(header.getValue()).append("\"");
}
String jsonBody = JsonFormat.printToString(message);
jsonBody = jsonBody.replace("\"", "\\\"");
sb.append(" -d \"").append(jsonBody).append("\"");
sb.append(" ").append(requestUrl);
System.out.println(sb.toString());
return httpclient.execute(post);
}
}
以debug方式运行SpringBoot项目,并在controller加断点,然后运行测试代码:
可以看到请求过来的数据是正确的,放行后可以看到响应数据也是正确的:
来源:https://blog.csdn.net/yanshaoshuai/article/details/103824463
标签:SpringBoot,protobuf,接口
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Kotlin开发Android应用实例详解
2023-09-11 00:22:50
![](https://img.aspxhome.com/file/2023/9/58149_0s.png)
Spring Boot2中如何优雅地个性化定制Jackson实现示例
2021-09-27 12:21:15
详解Spark Sql在UDF中如何引用外部数据
2021-08-17 14:51:17
![](https://img.aspxhome.com/file/2023/4/64124_0s.jpg)
SpringCloud分布式链路追踪组件Sleuth配置详解
2023-11-28 23:58:42
![](https://img.aspxhome.com/file/2023/6/60666_0s.png)
详解java WebSocket的实现以及Spring WebSocket
2023-11-24 13:16:25
![](https://img.aspxhome.com/file/2023/5/59885_0s.png)
Flutter 容器盒子模型的使用示例
2023-06-18 18:47:43
![](https://img.aspxhome.com/file/2023/4/85974_0s.png)
Java多线程Thread基础学习
2023-04-17 17:12:21
![](https://img.aspxhome.com/file/2023/8/67688_0s.png)
Spring中的aware接口详情
2023-11-29 10:48:29
![](https://img.aspxhome.com/file/2023/9/60689_0s.webp)
java日期格式化SimpleDateFormat的使用详解
2023-08-25 03:22:15
![](https://img.aspxhome.com/file/2023/0/58460_0s.png)
详解SpringBoot统一响应体解决方案
2023-03-08 08:54:13
linux环境下java程序打包成简单的hello world输出jar包示例
2023-11-26 11:11:37
![](https://img.aspxhome.com/file/2023/8/60378_0s.png)
centos 安装java环境的多种方法
2023-08-10 16:01:37
Spring项目中使用Junit单元测试并配置数据源的操作
2022-06-02 05:32:27
剑指Offer之Java算法习题精讲链表专项训练
2023-11-29 16:31:48
![](https://img.aspxhome.com/file/2023/1/60611_0s.png)
java ThreadGroup的作用及方法详解
2022-02-03 16:49:01
![](https://img.aspxhome.com/file/2023/2/60762_0s.jpg)
SpringBoot整合OpenApi的实践
2023-08-03 11:59:55
![](https://img.aspxhome.com/file/2023/8/70578_0s.jpg)
使用java打印心型、圆形图案的实现代码
2021-08-30 19:50:45
![](https://img.aspxhome.com/file/2023/9/66649_0s.jpg)
浅谈Java并发中的内存模型
2022-09-07 17:54:47
![](https://img.aspxhome.com/file/2023/3/62093_0s.png)
java的Arrays工具类实战
2023-08-21 15:46:36
![](https://img.aspxhome.com/file/2023/6/58076_0s.png)
Java调用wsdl接口的两种方法(axis和wsimport)
2023-06-23 14:41:22
![](https://img.aspxhome.com/file/2023/8/65338_0s.png)