spring mvc 4.1支持protobuf converters

最近公司有个项目需要和c++做信息交换,现在流行比较流行http+protobuf方式,一是比较简单学习成本低,二是信息的压缩比例比较好,节省带宽。

经过调研spring 4.1以后开始支持protobuf HttpMessageConverter 详细的配置如下:

  • pom.xml配置:
<dependency>    <groupId>com.google.protobuf</groupId>    <artifactId>protobuf-java</artifactId>    <version>2.5.0</version></dependency>
<dependency>    <groupId>com.googlecode.protobuf-java-format</groupId>    <artifactId>protobuf-java-format</artifactId>    <version>1.2</version></dependency>还有要引入spring核心包及spring mvc包 版本4.1.6.RELEASE,如果不知道怎么引入,百度一下

配置portoc插件,也可以不用这个插件,得需要自己用protoc.exe生产java文件
<plugin>    <groupId>com.google.protobuf.tools</groupId>    <artifactId>maven-protoc-plugin</artifactId>    <version>0.1.10</version>    <executions>        <execution>            <id>generate-sources</id>            <goals>                <goal>compile</goal>            </goals>            <phase>generate-sources</phase>            <configuration>                <protoSourceRoot>${basedir}/src/main/proto/</protoSourceRoot>                <includes>                    <param>**/*.proto</param>                </includes>            </configuration>        </execution>    </executions>    <configuration>        <protocExecutable>D:/dev/protoc.exe</protocExecutable><!--protoc.exe文件地址,使用2.5版本-->    </configuration></plugin>
  • springmvc-servlet.xml配置
<mvc:annotation-driven>    <mvc:message-converters>    <!--看了一下源码,客户端请求类型必须设置成application/x-protobuf采用用这个类来解析实体

        <bean class="org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter">
        </bean>    </mvc:message-converters></mvc:annotation-driven>
  • user.proto文件,目录/src/main/proto/和protoc插件配置路径保持一致,如果不想用插件可以自己用protoc.exe生成java文件,可以参见protobuf使用
package com.my.pb;

 option java_package = "com.my.pb";
 option java_outer_classname = "UserProto";

 message User {   optional int64 id = 1;   optional string name = 2;   message PhoneNumber {       required string number = 1;     }     repeated PhoneNumber phone = 4; }
  • controller类
@Controllerpublic class ProtobufController{

    @RequestMapping(value = "/proto/write1",method= RequestMethod.POST)    public ResponseEntity<UserProto.User> protoWrite1(RequestEntity<UserProto.User> requestEntity) {        //System.out.println("server===\n");        UserProto.User user =  requestEntity.getBody();        System.out.println("server===\n" + user);        return ResponseEntity.ok(user);    }}
  • 客户端测试代码,使用Apache的httpclient进行测试
@Test    public void testWrite() throws IOException {        CloseableHttpClient httpclient = HttpClients.createDefault();        HttpPost httpPost = new HttpPost(baseUri+"/proto/write1");

        UserProto.User user =   UserProto.User.newBuilder().setId(1).setName("zhangsan").addPhone(UserProto.User.PhoneNumber.newBuilder().setNumber("18611163408")).build();//构造

        ByteArrayInputStream inputStream = new ByteArrayInputStream(user.toByteArray());        InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream);

    //这两行很重要的,是告诉springmvc客户端请求和响应的类型,指定application/x-protobuf类型,spring会用ProtobufHttpMessageConverter类来解析请求和响应的实体
        httpPost.addHeader("Content-Type","application/x-protobuf");        httpPost.addHeader("Accept", "application/x-protobuf");

     httpPost.setEntity(inputStreamEntity);        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {            System.out.println(response2.getStatusLine());            HttpEntity entity2 = response2.getEntity();

            ByteArrayOutputStream buf = new ByteArrayOutputStream();            entity2.writeTo(buf);            System.out.println(new String(buf.toByteArray())+"#################");            UserProto.User user2 = UserProto.User.parseFrom(buf.toByteArray());            System.out.println(user2);        } finally {            response2.close();        }    }
  • 总结:
当时调试的时候试了很多次,响应总是被转成xml类型,最后看了源码才发现客户端要设置httpPost.addHeader("Accept", "application/x-protobuf");其实也可以自己实现HttpMessageConverter,也不是很麻烦,本人比较懒,有现成的东西不太爱闭门造车轮。
参考文献:http://jinnianshilongnian.iteye.com/blog/2107205http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/
时间: 2024-08-05 14:14:47

spring mvc 4.1支持protobuf converters的相关文章

Spring MVC http请求地址映射(三)

Spring MVC框架通过扫描将带有@Controller的类中的@RequestMapping的方法进行映射,然后调用映射的方法处理请求,这个分发过程默认是由DispaterServlet处理的. http请求映射原理 Spring MVC进行映射的依据 通过URL限定:URL表达式 Spring MVC的地址映射支持标准的URL,同时默认支持是ant风格的URL.列如: URL 说明 /account/*/create 匹配/account/aaa/create./account/bbb/

Spring MVC学习:处理方法返回值的可选类型

spring mvc处理方法支持如下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void. * ModelAndView Java代码 1. @RequestMapping("/show1") 2. public ModelAndView show1(HttpServletRequest request, 3. HttpServletResponse response) throws Exception { 4. Mod

Spring MVC 基础篇 2

Spring MVC 与rest支持 [email protected] 映射URL绑定的占位符 通过@PathVariable可以将URL上占位符参数绑定到控制器处理方法的入参中:URL中的{XXX}占位符可以通过@PathVariable("xxx")绑定到操作方法的入参中. @RequestMapping(value="/hello/{name}") public String hello(@PathVariable("name") Str

Spring MVC 与 web开发

转载:http://coderbee.net/index.php/java/20140719/959 项目组用了 Spring MVC 进行开发,觉得对里面的使用方式不是很满意,就想,如果是我来搭建开发环境,我会怎么做?下面就是我的想法,只关注于 MVC 的 View 层. 一.统一的响应格式 现在基本上都是用 ajax 来调用后台接口,拿到 json格式的数据再展示,有的人直接返回数据,却没有考虑异常的情况,我觉得返回的报文里必须包含表示可能的异常信息的数据和业务响应数据.我定义了下面这个类来

Spring MVC学习之三:处理方法返回值的可选类型

转自:http://www.cnblogs.com/cuizhf/p/3810652.html ———————————————————————————————————————————————————————————— spring mvc处理方法支持如下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void.下面将对具体的一一进行说明: ModelAndView @RequestMapping("/show1") publ

Spring+Spring MVC+Mybatis+Maven搭建多模块项目(一)

Spring+Spring MVC+Mybatis+Maven搭建多模块项目(一) 标签:               springmvcspring mvcmybatismaven 2016-11-22 22:27             4425人阅读             评论(1)             收藏              举报 .embody { padding: 10px 10px 10px; margin: 0 -20px; border-bottom: solid

Spring MVC之中前端向后端传数据

Spring MVC之中前端向后端传数据 Spring MVC之中前端向后端传数据和后端向前端传数据是数据流动的两个方向, 在此先介绍前端向后端传数据的情况. 一般而言, 前端向后端传数据的场景, 大多是出现了表单的提交,form表单的内容在后端学习的md文档之中有所介绍,form标签的语法格式如下 <FORM NAME="FORM1" ACTION="URL" METHOD="GET|POST" ENCTYPE="MIME&qu

Spring MVC关于IE对application/json的content-type不支持解决方案---duang 解决了

在现代的web开发中,我们为了用户的体验广泛的使用异步开发,用户看不见后台的实际执行情况,只关心结果,所以良好的提示消息决定了系统对用户的态度,所以要开发一套标准的提示消息,我选择了JSON,但是在实际开发过程中,会发现IE不支持application/json类型,所以我也在网上查找了好多同样的问题,但是大部分说法都是注册注册表,但是我门发布系统又不能让每个用户都注册一下注册表,这显然很不合理,所以我发现,只要修改返回的内容的类型(ContentType)即可解决问题. 1,默认情况下,我们会

Spring MVC 文件下载时候 发现IE不支持

@RequestMapping("download") public ResponseEntity<byte[]> download(Long fileKey) throws IOException { HttpHeaders headers = new HttpHeaders(); String fileName=new String(massMessage.getFileName().getBytes("UTF-8"),"iso-8859-