Protostuff使用入门[通俗易懂]

Protostuff使用入门[通俗易懂]ProtostuffThegoalofprotostuffistogenerateaschemawhetheratcompile-timeorruntimeandusethatforreading/writingtovariousformatsviatheprovidedIOlibs.SchemaAclassthatencapsu…

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

Protostuff

The goal of protostuff is to generate a schema whether at compile-time or runtime and use that for reading/writing to various formats via the provided IO libs.

Schema

A class that encapsulates:

  • the serialization logic of an object
  • the deserialization logic of an object
  • the validation of an object’s required fields
  • the mapping of an object’s field names to field numbers
  • the instantiation of the object.

For existing objects, use protostuff-runtime which uses reflection.

示例

User类是个简单的pojo类:

package demo.domain;

import lombok.Data;
import java.util.List;

@Data
public class User { 
   
    private String firstName;
    private String lastName;
    private String email;
    private List<User> friends;
}

定义User的序列化逻辑:UserSchema

package demo.serializing;

import demo.domain.User;
import io.protostuff.Input;
import io.protostuff.Output;
import io.protostuff.Schema;
import io.protostuff.UninitializedMessageException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class UserSchema implements Schema<User> { 
   

    private static final HashMap<String, Integer> fieldMap = new HashMap<>();
    static { 
   
        fieldMap.put("email", 1);
        fieldMap.put("firstName", 2);
        fieldMap.put("lastName", 3);
        fieldMap.put("friends", 4);
    }

    @Override
    public String getFieldName(int number) { 
   
        switch (number) { 
   
            case 1:
                return "email";
            case 2:
                return "firstName";
            case 3:
                return "lastName";
            case 4:
                return "friends";
            default:
                return null;
        }
    }

    @Override
    public int getFieldNumber(String name) { 
   
        Integer number = fieldMap.get(name);
        return number == null ? 0 : number;
    }

    @Override
    public boolean isInitialized(User message) { 
   
        return message.getEmail() != null;
    }

    @Override
    public User newMessage() { 
   
        return new User();
    }

    @Override
    public String messageName() { 
   
        return User.class.getSimpleName();
    }

    @Override
    public String messageFullName() { 
   
        return User.class.getName();
    }

    @Override
    public Class<? super User> typeClass() { 
   
        return User.class;
    }

    @Override
    public void mergeFrom(Input input, User message) throws IOException { 
   
        while (true) { 
   
            int number = input.readFieldNumber(this);
            switch (number) { 
   
                case 0:
                    return;
                case 1:
                    message.setEmail(input.readString());
                    break;
                case 2:
                    message.setFirstName(input.readString());
                    break;
                case 3:
                    message.setLastName(input.readString());
                    break;
                case 4:
                    if (message.getFriends() == null)
                        message.setFriends(new ArrayList<>());
                    message.getFriends().add(input.mergeObject(null, this));
                    break;
                default:
                    input.handleUnknownField(number, this);
            }
        }
    }

    @Override
    public void writeTo(Output output, User user) throws IOException { 
   
        if (user.getEmail() == null)
            throw new UninitializedMessageException(user, this);
        output.writeString(1, user.getEmail(), false);

        if (user.getFirstName() != null)
            output.writeString(2, user.getFirstName(), false);

        if (user.getLastName() != null)
            output.writeString(3, user.getLastName(), false);

        if (user.getFriends() != null) { 
   
            for (User friend : user.getFriends()) { 
   
                if (friend != null)
                    output.writeObject(4, friend, this, true);
            }
        }
    }

}

序列化和反序列化示例:

package demo;

import demo.domain.User;
import demo.serializing.UserSchema;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import lombok.extern.java.Log;

import java.util.ArrayList;
import java.util.List;

@Log
public class App { 
   

    public static void main(String[] args) { 
   
        User user1 = new User();
        user1.setEmail("1178449100@qq.com");
        user1.setFirstName("wenwen");
        user1.setLastName("zha");

        User user2 = new User();
        user2.setEmail("gumengqin@qq.com");
        List<User> users = new ArrayList<>();
        users.add(user2);
        user1.setFriends(users);

        Schema<User> schema = new UserSchema();
        byte[] data;
        data = ProtostuffIOUtil.toByteArray(user1, schema, LinkedBuffer.allocate());
        log.info("序列化完成:" + data.length);

        User newUser = new User();
        ProtostuffIOUtil.mergeFrom(data, newUser, schema);
        log.info("反序列化完成:" + newUser);
    }

}

RuntimeSchema

使用RuntimeSchema可以不用自定义Schema,省了不少工作。

package demo.serializing;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ProtostuffUtils { 
   

    //避免每次序列化都重新申请Buffer空间
    private static LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    //缓存Schema
    private static Map<Class<?>, Schema<?>> schemaCache = new ConcurrentHashMap<Class<?>, Schema<?>>();

    //序列化方法,把指定对象序列化成字节数组
    @SuppressWarnings("unchecked")
    public static <T> byte[] serialize(T obj) { 
   
        Class<T> clazz = (Class<T>) obj.getClass();
        Schema<T> schema = getSchema(clazz);
        byte[] data;
        try { 
   
            data = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } finally { 
   
            buffer.clear();
        }
        return data;
    }

    //反序列化方法,将字节数组反序列化成指定Class类型
    public static <T> T deserialize(byte[] data, Class<T> clazz) { 
   
        Schema<T> schema = getSchema(clazz);
        T obj = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, obj, schema);
        return obj;
    }

    @SuppressWarnings("unchecked")
    private static <T> Schema<T> getSchema(Class<T> clazz) { 
   
        Schema<T> schema = (Schema<T>) schemaCache.get(clazz);
        if (schema == null) { 
   
            schema = RuntimeSchema.getSchema(clazz);
            if (schema != null) { 
   
                schemaCache.put(clazz, schema);
            }
        }
        return schema;
    }
}

重新测试:

package demo;

import demo.domain.User;
import demo.serializing.ProtostuffUtils;
import lombok.extern.java.Log;

import java.util.ArrayList;
import java.util.List;

@Log
public class App { 
   

    public static void main(String[] args) { 
   
        User user1 = new User();
        user1.setEmail("1178449100@qq.com");
        user1.setFirstName("wenwen");
        user1.setLastName("zha");

        User user2 = new User();
        user2.setEmail("gumengqin@qq.com");
        List<User> users = new ArrayList<>();
        users.add(user2);
        user1.setFriends(users);


        byte[] data = ProtostuffUtils.serialize(user1);
        log.info("序列化完成:" + data.length);

        User newUser=ProtostuffUtils.deserialize(data,User.class);
        log.info("反序列化完成:" + newUser);
    }

}

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

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

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


相关推荐

  • python to exe transporter: py2exe Test report「建议收藏」

    python to exe transporter: py2exe Test report「建议收藏」pipinstallpy2exefromdistutils.coreimportsetupimportpy2exesetup(windows=[{“script”:”123.py”}])Thisreportisonlyusedtorecord.

    2022年9月11日
    0
  • idea 集成svn_idea从svn拉代码

    idea 集成svn_idea从svn拉代码IDEA集成SVN代码管理常用功能

    2022年10月17日
    0
  • 将WebStorm快捷键修改为eclipse的快捷键风格

    将WebStorm快捷键修改为eclipse的快捷键风格说明:由于大家都熟练使用了eclipse、MyEclipse等软件,其快捷键也应用熟练,所以大家在用WebStorm时,可以将WebStorm的快捷键风格(映射)改为大家常用的eclipse风格快捷键。 修改方法  File(文件)–&gt;Settings…(设置…)–&gt;快捷键–&gt;Keymap(快捷键映射)下拉选择eclipse,应用确定即可。  …

    2022年6月23日
    31
  • android常用布局详解「建议收藏」

    android常用布局详解「建议收藏」view和布局在一个Android应用程序中,用户界面通过View和ViewGroup对象构建。Android中有很多种View和ViewGroup,他们都继承自View类。View对象是Android平台上表示用户界面的基本单元。View的布局显示方式直接影响用户界面,View的布局方式是指一组View元素如何布局,准确的说是一个ViewGroup中包含的一些View怎么样布局。ViewGr…

    2022年6月2日
    31
  • python 函数进阶与闭包

    函数的命名空间和作用域引言现在有个问题,函数里面的变量,在函数外面能直接引用么?上面为什么会报错呢?现在我们来分析一下python内部的原理是怎么样:我们首先回忆一下Python代码运行的时候

    2022年3月29日
    39
  • 华为 NTP协议「建议收藏」

    华为 NTP协议「建议收藏」概述NTP是从时间协议(timeprotocol)和ICMP时间戳报文(ICMPTimeStampMessage)演变而来,在准确性和健壮性方面进行了特殊的设计,理论上精确可达十亿分之一秒。NTP协议应用于分布式时间服务器和客户端之间,实现客户端和服务器的时间同步,从而使网络内所有设备的时钟基本保持一致。NTP协议是基于UDP进行传输的,使用端口号为123。‘NTP的优势采用分层(Stratum)的方法来定义时钟的准确性,可以迅速同步网络中各台设备的时间。持访问控制和MD5

    2022年10月12日
    0

发表回复

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

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