【序列化和反序列化】Protostuff
一、protostuff介绍
protostuff基于Google protobuf ,但是提供了更多的功能和更简易的用法。其中,protostuff-runtime实现了无需预编译对java bean进行protobuf序列化/反序列化的能力。protostuff-runtime的局限是序列化前需预先传入schema,反序列化不负责对象的创建只负责复制,因此必须提供默认构造函数。在性能上,protostuff不输原生的protobuf,甚至有反超之势
二、protostuff用法
maven
<dependency> <groupId>io.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>io.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>1.7.4</version> </dependency>
工具类
package com.chenly.serialize.protostuff; import com.chenly.serialize.bean.Score; import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema;; /** * @author: chenly * @date: 2022-12-06 14:56 * @description: * @version: 1.0 */ public class ProtostuffTest2 { public static void main(String[] args) { Score score = Score.builder() .className("一班") .stuName("张三").course("生物").score(90).build(); long startTime = System.currentTimeMillis(); //序列化 byte[] bytes = serialize(score); //反序列化 Score object = deserialize(bytes,Score.class); System.out.println(object); System.out.println("耗时:"+(System.currentTimeMillis()-startTime)/1000.00); } /** 序列化 */ public static <T> byte[] serialize(T obj) { Class<T> cls = (Class<T>) obj.getClass(); // this is lazily created and cached by RuntimeSchema // so its safe to call RuntimeSchema.getSchema(Foo.class) over and over // The getSchema method is also thread-safe Schema<T> schema = RuntimeSchema.getSchema(cls); // Re-use (manage) this buffer to avoid allocating on every serialization LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); //序列化 byte[] protostuff; try{ protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer); return protostuff; }catch (Exception e){ e.printStackTrace(); return null; }finally { buffer.clear(); } } /** 反序列化 */ public static <T> T deserialize(byte[] bytes,Class<T> cls) { Schema<T> schema = RuntimeSchema.getSchema(cls); // 反序列化 T obj = schema.newMessage(); ProtostuffIOUtil.mergeFrom(bytes, obj, schema); return obj; } }
参考地址:
github地址: https://github.com/protostuff/protostuff
作者:小念
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律