如果要实现高效的编解码可以用protobuf,但是protobuf需要维护大量的proto文件比较麻烦,现在一般可以使用protostuff。 protostuff是一个基于protobuf实现的序列化方法,它较于protobuf最明显的好处是,在几乎不损耗性能的情况下做到了不用我们
写.proto文件来实现序列化。使用它也非常简单,代码如下:
引入依赖:
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-api</artifactId>
<version>1.7.4</version>
</dependency>
<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>
/**
* @Author lcx
* @Description
* @Date 2022/8/8 17:28
*/
public class ProtostuffUtil {
public static <T> byte[] serializer(T o) {
Schema schema = RuntimeSchema.getSchema(o.getClass());
return ProtobufIOUtil.toByteArray(o, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
}
public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
T obj = null;
try {
//默认无参数构造函数
obj = clazz.newInstance();
Schema schema = RuntimeSchema.getSchema(obj.getClass());
ProtostuffIOUtil.mergeFrom(bytes, obj, schema);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] userBytes = ProtostuffUtil.serializer(new User("111","2222"));
for (byte b:userBytes){
System.out.print(b);
}
System.out.println();
User user = ProtostuffUtil.deserializer(userBytes, User.class);
System.out.println(user);
}
}