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,接口
0
投稿
猜你喜欢
SpringBoot @ConfigurationProperties注解的简单使用
2021-09-03 12:21:57
C#域名解析简单实现方法
2023-08-26 15:30:55
java文件输出流写文件的几种方法
2023-11-08 16:17:30
C#简单数字图像处理程序
2022-03-07 05:16:31
MyBatis实现模糊查询的几种方式
2023-06-03 17:31:43
Java将对象保存到文件中/从文件中读取对象的方法
2022-06-18 21:26:42
Java string类型转换成map代码实例
2021-06-07 12:19:29
Java8简单了解Lambda表达式与函数式接口
2022-11-07 00:22:31
C# ComboBox控件“设置 DataSource 属性后无法修改项集合”的完美解决方法
2023-01-30 04:11:58
springcloud 如何解决微服务之间token传递问题
2022-08-27 18:43:48
Android apk 插件启动内存释放问题
2022-05-16 07:26:39
Android中TabLayout+ViewPager实现tab和页面联动效果
2022-02-23 22:41:49
SpringBoot @SpringBootTest加速单元测试的小诀窍
2022-12-17 13:05:06
Android直播软件搭建之实现背景颜色滑动渐变效果的详细代码
2022-03-24 21:18:54
java中类加载与双亲委派机制详解
2023-12-07 06:34:53
Android 通知栏的使用方法
2022-11-12 20:00:29
c++函数转c#函数示例程序分享
2023-08-13 14:45:26
android自定义View圆圈拖动
2023-09-14 01:02:55
java中Integer包装类装箱的一个细节详解
2023-09-24 18:35:32
Android 自定义圆形带刻度渐变色的进度条样式实例代码
2023-11-23 13:21:38