Protostuff开发

Protostuff开发Protostuff开发作者:chszs,未经博主允许不得转载。经许可的转载需注明作者和博客主页:http://blog.csdn.net/chszs五、Protostuff用法1、为Java实体产生schemasio.protostuffprotostuff-core<

大家好,又见面了,我是你们的朋友全栈君。

Protostuff开发

作者:chszs,未经博主允许不得转载。经许可的转载需注明作者和博客主页:http://blog.csdn.net/chszs

五、Protostuff用法

1、为Java实体产生schemas

<dependency>
  <groupId>io.protostuff</groupId>
  <artifactId>protostuff-core</artifactId>
  <version>1.3.8</version>
</dependency>

2、Runtime schemas

<dependency>
  <groupId>io.protostuff</groupId>
  <artifactId>protostuff-runtime</artifactId>
  <version>1.3.8</version>
</dependency>

3、Protostuff的Maven插件

Protostuff的Maven插件可以从.proto文件中生成Java源码或其它语言的源码——通过使用基于StringTemplate的代码生成器(或扩展)。
下面讲述此插件的用法。

1)项目的结构如下:

<project root>
├───pom.xml
└───src
    └───main
        └───proto
            └───hello.proto

Protocol buffer定义路径是可配置的,但是推荐使用src/main/proto/路径。所有的.proto文件及其子目录都放于此目录下,且会被protobuf定义视为包结构,以import方式导入。

hello.proto的内容如下:

package search;

option java_package = "stuff.ch";

message HelloRequest {
    optional string name = 1;
}

message HelloResponse {
    optional string greeting = 1;
}

service HelloService {
    rpc hello (HelloRequest) returns (HelloResponse);
}

执行命令:

mvn protostuff:compile

在项目目录下产生相应的Java文件。

<project root>
├───pom.xml
└───target
    └───generated-sources
        └───proto
            └───stuff
                └───ch
                    └───HelloRequest.java
                    └───HelloResponse.java

HelloRequest.java的内容如下:

// Generated by http://code.google.com/p/protostuff/ ... DO NOT EDIT!
// Generated from proto

package stuff.ch;

import javax.annotation.Generated;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;

import io.protostuff.GraphIOUtil;
import io.protostuff.Input;
import io.protostuff.Message;
import io.protostuff.Output;
import io.protostuff.Schema;

@Generated("java_bean")
public final class HelloRequest implements Externalizable, Message<HelloRequest>, Schema<HelloRequest> {

    public static Schema<HelloRequest> getSchema() {
        return DEFAULT_INSTANCE;
    }

    public static HelloRequest getDefaultInstance() {
        return DEFAULT_INSTANCE;
    }

    static final HelloRequest DEFAULT_INSTANCE = new HelloRequest();

    private String name;

    public HelloRequest() {

    }

    // getters and setters

    // name

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || this.getClass() != obj.getClass()) {
            return false;
        }
        final HelloRequest that = (HelloRequest) obj;
        return Objects.equals(this.name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public String toString() {
        return "HelloRequest{" + "name=" + name + '}';
    }
    // java serialization

    public void readExternal(ObjectInput in) throws IOException {
        GraphIOUtil.mergeDelimitedFrom(in, this, this);
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        GraphIOUtil.writeDelimitedTo(out, this, this);
    }

    // message method

    public Schema<HelloRequest> cachedSchema() {
        return DEFAULT_INSTANCE;
    }

    // schema methods

    public HelloRequest newMessage() {
        return new HelloRequest();
    }

    public Class<HelloRequest> typeClass() {
        return HelloRequest.class;
    }

    public String messageName() {
        return HelloRequest.class.getSimpleName();
    }

    public String messageFullName() {
        return HelloRequest.class.getName();
    }

    public boolean isInitialized(HelloRequest message) {
        return true;
    }

    public void mergeFrom(Input input, HelloRequest message) throws IOException {
        for (int number = input.readFieldNumber(this);; number = input.readFieldNumber(this)) {
            switch (number) {
            case 0:
                return;
            case 1:
                message.name = input.readString();
                break;
            default:
                input.handleUnknownField(number, this);
            }
        }
    }

    public void writeTo(Output output, HelloRequest message) throws IOException {
        if (message.name != null)
            output.writeString(1, message.name, false);
    }

    public String getFieldName(int number) {
        return Integer.toString(number);
    }

    public int getFieldNumber(String name) {
        return Integer.parseInt(name);
    }

}

HelloResponse.java的内容如下:

// Generated by http://code.google.com/p/protostuff/ ... DO NOT EDIT!
// Generated from proto

package stuff.ch;

import javax.annotation.Generated;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;

import io.protostuff.GraphIOUtil;
import io.protostuff.Input;
import io.protostuff.Message;
import io.protostuff.Output;
import io.protostuff.Schema;

@Generated("java_bean")
public final class HelloResponse implements Externalizable, Message<HelloResponse>, Schema<HelloResponse> {

    public static Schema<HelloResponse> getSchema() {
        return DEFAULT_INSTANCE;
    }

    public static HelloResponse getDefaultInstance() {
        return DEFAULT_INSTANCE;
    }

    static final HelloResponse DEFAULT_INSTANCE = new HelloResponse();

    private String greeting;

    public HelloResponse() {

    }

    // getters and setters

    // greeting

    public String getGreeting() {
        return greeting;
    }

    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || this.getClass() != obj.getClass()) {
            return false;
        }
        final HelloResponse that = (HelloResponse) obj;
        return Objects.equals(this.greeting, that.greeting);
    }

    @Override
    public int hashCode() {
        return Objects.hash(greeting);
    }

    @Override
    public String toString() {
        return "HelloResponse{" + "greeting=" + greeting + '}';
    }
    // java serialization

    public void readExternal(ObjectInput in) throws IOException {
        GraphIOUtil.mergeDelimitedFrom(in, this, this);
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        GraphIOUtil.writeDelimitedTo(out, this, this);
    }

    // message method

    public Schema<HelloResponse> cachedSchema() {
        return DEFAULT_INSTANCE;
    }

    // schema methods

    public HelloResponse newMessage() {
        return new HelloResponse();
    }

    public Class<HelloResponse> typeClass() {
        return HelloResponse.class;
    }

    public String messageName() {
        return HelloResponse.class.getSimpleName();
    }

    public String messageFullName() {
        return HelloResponse.class.getName();
    }

    public boolean isInitialized(HelloResponse message) {
        return true;
    }

    public void mergeFrom(Input input, HelloResponse message) throws IOException {
        for (int number = input.readFieldNumber(this);; number = input.readFieldNumber(this)) {
            switch (number) {
            case 0:
                return;
            case 1:
                message.greeting = input.readString();
                break;
            default:
                input.handleUnknownField(number, this);
            }
        }
    }

    public void writeTo(Output output, HelloResponse message) throws IOException {
        if (message.greeting != null)
            output.writeString(1, message.greeting, false);
    }

    public String getFieldName(int number) {
        return Integer.toString(number);
    }

    public int getFieldNumber(String name) {
        return Integer.parseInt(name);
    }

}

编写HelloService.java,内容如下:

package stuff.ch;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.Schema;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HelloService {
    public static final Schema<HelloRequest> SEARCH_REQUEST_SCHEMA = HelloRequest.getSchema();
    public static final Schema<HelloResponse> SEARCH_RESPONSE_SCHEMA = HelloResponse.getSchema();

    /**
     * Sample "hello" rpc method handler.
     *
     * @param requestData
     *            {@code HelloRequest} binary array encoded using Protocol
     *            Buffers
     * @return {@code HelloResponse} binary array encoded using Protocol Buffers
     */
    public byte[] hello(byte[] requestData) throws IOException {
        HelloRequest request = deserialize(requestData);
        HelloResponse response = hello(request);
        return serialize(response);
    }

    private byte[] serialize(HelloResponse response) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        LinkedBuffer buffer = LinkedBuffer.allocate();
        ProtobufIOUtil.writeTo(outputStream, response, SEARCH_RESPONSE_SCHEMA, buffer);
        return outputStream.toByteArray();
    }

    private HelloRequest deserialize(byte[] requestData) {
        HelloRequest request = SEARCH_REQUEST_SCHEMA.newMessage();
        ProtobufIOUtil.mergeFrom(requestData, request, SEARCH_REQUEST_SCHEMA);
        return request;
    }

    /**
     * Service method implementation.
     */
    private HelloResponse hello(HelloRequest request) {
        HelloResponse response = new HelloResponse();
        String name = request.getName();
        response.setGreeting("Hello, " + name);
        return response;
    }
}

编写单元测试类HelloServiceTest.java,内容如下:

package stuff.ch;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class HelloServiceTest {
    public static final byte[] REQUEST = new byte[] { 0x0A, 0x03, '4', '2', '!' };
    public static final byte[] RESPONSE = new byte[] { 0x0A, 0x0A, 'H', 'e', 'l', 'l', 'o', ',', ' ', '4', '2', '!' };

    private HelloService service;

    @Before
    public void setUp() throws Exception {
        service = new HelloService();
    }

    @Test
    public void testSearch() throws Exception {
        byte[] responseData = service.hello(REQUEST);
        Assert.assertArrayEquals(RESPONSE, responseData);
    }
}

运行单元测试,测试通过。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/133862.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java交换二维数组行列_java二维数组行列

    java交换二维数组行列_java二维数组行列培训系列AmberXie求二维数组行列之和把二维数组a各行之和分别放入b…二维数组例题答案[技巧]【例1】编写程序,利用二维数组在窗体上输出如图5×5…如果没有max为行列都是最大值flag=0Forj=1To5Ifa(j……二维数组行列数的检测也是通过属性length进行的,不同的是测列数时需要给定一…程序中定义了二维数组arr,a…

    2022年6月7日
    48
  • pycharm配置svn有什么用_SVN安装配置

    pycharm配置svn有什么用_SVN安装配置PyCharm是一款非常优秀的PythonIDE,以前用Editplus,用惯了感觉还行。用了PyCharm后被它丰富的功能吸引了。无论是普通python脚本、Django框架项目、还是GoogleAppEngine项目,它都能完美运行。不过设置起来比较麻烦,比如Subversion的用法我就一直没参透,我总是写完代码后出去用小乌龟提交。今天google一下,终于搞定了。现在写完代码后直接在…

    2022年8月26日
    4
  • Java_BigDecimal类型比较大小

    Java_BigDecimal类型比较大小这个类是java里精确计算的类1比较对象是否相等一般的对象用equals,但是BigDecimal比较特殊,举个例子:BigDecimala=BigDecimal.valueOf(1.0);BigDecimalb=BigDecimal.valueOf(1.000);在现实中这两个数字是相等的,但是问题来来了…

    2022年7月14日
    23
  • 哪些软件是python编写出来的_用Python编程需要什么软件?

    哪些软件是python编写出来的_用Python编程需要什么软件?用Python编程需要什么软件?Python编程是一门适合新手入门的编程语言,现在有不少程序员业余时间学习Python编程语言,学习Python找到好工具会大大提高学习的效率。好用的Python编程软件能将工作效率多倍速提升。今天小编就介绍一些Python编程软件供大家参考:一、终端:UptermUpterm简单好用,它是一个全平台的终端,可以说是终端里的IDE,有着强大的自动补全功能。二、交互式…

    2022年5月23日
    70
  • HttpClient4.x 使用cookie保持会话

    HttpClient4.x 使用cookie保持会话HttpClient4.x可以自带维持会话功能,只要使用同一个HttpClient且未关闭连接,则可以使用相同会话来访问其他要求登录验证的服务(见TestLogin()方法中的“执行get请求”部分)。如果需要使用HttpClient池,并且想要做到一次登录的会话供多个HttpClient连接使用,就需要自己保存会话信息。因为客户端的会话信息是保存在cookie中的(JSESSIONID),所

    2022年7月22日
    11
  • 安卓中listview的使用步骤_安卓listview控件的用法

    安卓中listview的使用步骤_安卓listview控件的用法1)排序ListView通过适配器得到内容数据,可以对数据list先排序再提供给ListView:privateList>getData(){List>list=newArrayList>();//addData…//对list进行排序if(!list.isEmpty()){Collections.sort(list,newComparator&g…

    2022年9月28日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号