avatar

protostuff序列化工具

介绍

在很多地方都需要用到序列化, 比如在使用redis缓存对象时, 一般情况是实现java Serializable接口. 简单介绍下在慕课网学习到的一个新的序列化工具 —- protostuff.

在学习中介绍使用该工具可以大大减少对象序列化后字节所占空间, 并提高序列化时间等.

1.慕课网课程地址
2.序列化相关工具比较

引入依赖

<!-- protostuff 序列化工具 -->
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.1.3</version>
</dependency>

相关使用

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

/**
* @author liuzhihang
* @date 2018/4/18 15:04
*/
public class ProtostuffUtil {

public static <T> byte[] serialize(T t, Class<T> cls) {

RuntimeSchema<T> schema = RuntimeSchema.createFrom(cls);

return ProtostuffIOUtil.toByteArray(t, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
}

public static <T> T unSerialize(byte[] bytes, Class<T> cls) {

RuntimeSchema<T> schema = RuntimeSchema.createFrom(cls);
T message = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes, message, schema);

return message;
}

}

测试

import lombok.Data;

/**
* @author liuzhihang
* @date 2018/4/17 19:01
*/
@Data
public class User {

private String id;

private String userName;

}

import com.alibaba.fastjson.JSON;

/**
* @author liuzhihang
* @date 2018/4/17 19:02
*/
public class ProtostuffTest {

public static void main(String[] args) {

User user = new User();
user.setId("test0001");
user.setUserName("测试用户0001");

System.out.println(JSON.toJSONString(user));

byte[] serialize = ProtostuffUtil.serialize(user, User.class);

User unSerialize = ProtostuffUtil.unSerialize(serialize, User.class);

System.err.println(JSON.toJSONString(unSerialize));

}

}

结果:
{"id":"test0001","userName":"测试用户0001"}
{"id":"test0001","userName":"测试用户0001"}
文章作者: liuzhihang
文章链接: https://liuzhihang.com/2018/02/05/protostuff-serialization-tool.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Notes

评论