• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot使用protobuf格式的接口方式

springboot 搞代码 4年前 (2022-01-05) 97次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了SpringBoot使用protobuf格式的接口方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringBoot使用protobuf格式的接口

建立SpringBoot项目,pom.xml内容如下:

   4.0.0 org.springframework.bootspring-boot-starter-parent2.2.2.RELEASE<!-- lookup parent from repository -->com.example.protobufdemo0.0.1-SNAPSHOTdemoDemo project for Spring Boot 1.8  org.springframework.bootspring-boot-starter org.springframework.bootspring-boot-starter-testtest  org.junit.vintagejunit-vintage-engine com.google.protobufprotobuf-java3.11.0 com.google.protobufprotobuf-java-util3.11.0 com.googlecode.protobuf-java-formatprotobuf-java-format1.2<!-- 网络请求依赖 --> org.apache.httpcomponentshttpclient4.5.2 org.apache.httpcomponentshttpcore4.4 org.springframework.bootspring-boot-starter org.springframework.bootspring-boot-starter-web org.apache.commonscommons-lang33.0 commons-collectionscommons-collections3.0   o<strong style="color:transparent">来源gaodai#ma#com搞@代~码网</strong>rg.springframework.bootspring-boot-maven-plugin

编写.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加断点,然后运行测试代码:

可以看到请求过来的数据是正确的,放行后可以看到响应数据也是正确的:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持gaodaima搞代码网

以上就是SpringBoot使用protobuf格式的接口方式的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot使用protobuf格式的接口方式
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址