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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 物联网架构设计「建议收藏」

    物联网架构设计「建议收藏」在设计lan(Github:https://github.com/phodal/lan)物联网平台的时候,结合之前的一些经验,构建出一个实际应用中的物联网构架模型。然后像lan这样的应用,在里面刚属于服务层。物联网层级结构通常,我们很容易在网上看到如下图所示的三层结构:从理论上划分这样的层级结构是没有问题的,也是有各种理…

    2025年11月27日
    3
  • 分类模型 第1篇:分类模型概述[通俗易懂]

    分类模型 第1篇:分类模型概述[通俗易懂]机器学习主要用于解决分类、回归和聚类问题,分类属于监督学习算法,是指根据已有的数据和标签(分类的类别)进行学习,预测未知数据的标签。分类问题的目标是预测数据的类别标签(classlabel),可以把

    2022年8月2日
    7
  • yarn详细入门教程「建议收藏」

    yarn详细入门教程「建议收藏」简介Yarn是Facebook,Google,Exponent和Tilde开发的一款新的JavaScript包管理工具。就像我们可以从官方文档了解那样,它的目的是解决这些团队使用npm面临的少数问题,即:1.安装的时候无法保证速度/一致性2.安全问题,因为npm安装时允许运行代码Yarn同样是一个从npm注册源获取模块的新的CLI客户端。注册的方

    2022年6月5日
    38
  • gis中char是什么字段_gis中字段类型char

    gis中char是什么字段_gis中字段类型char维护一个字符串集合,支持两种操作:I x 向集合中插入一个字符串 x;Q x 询问一个字符串在集合中出现了多少次。共有 N 个操作,输入的字符串总长度不超过 105,字符串仅包含小写英文字母。输入格式第一行包含整数 N,表示操作数。接下来 N 行,每行包含一个操作指令,指令为 I x 或 Q x 中的一种。输出格式对于每个询问指令 Q x,都要输出一个整数作为结果,表示 x 在集合中出现的次数。每个结果占一行。数据范围1≤N≤2∗104输入样例:5I abcQ abcQ ab

    2022年8月9日
    6
  • 飞机订票系统源代码

    飞机订票系统源代码问题及代码:/****************************************************  *版权所有(C)2017,张思琦 *文件名称:飞机订票系统  *文件标识:无  *内容摘要:实现录入航班信息、订票、退票、预约、 *          查询航班、查询订单、查看预约、修改航班功能。 *其他内容:无  *当前版本:VC++6.0  *作    者:

    2022年6月16日
    29
  • android scaleanimation动画,【Android动画九章】-RotateAnimation(旋转动画)和ScaleAnimation(尺寸动画)…[通俗易懂]

    android scaleanimation动画,【Android动画九章】-RotateAnimation(旋转动画)和ScaleAnimation(尺寸动画)…[通俗易懂]【Android动画九章】-RotateAnimation(旋转动画)和ScaleAnimation(尺寸动画)publicabstractclassAnimationextendsObjectimplementsCloneablejava.lang.Object↳Android.view.animation.AnimationKnownDirectSubclassesAlphaAn…

    2022年8月31日
    3

发表回复

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

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