因为protobuf用起来不太方便,然后产生了protostuff——Protostuff is the stuff that leverages google's protobuf.
1、maven依赖:
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.6.0</version>
</dependency>
或者
<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>
代码:
序列化对象User类:
package com.java.protostuff.dyuproject;
import lombok.Data;
@Data
public class User {
private String name;
private int age;
}
序列化工具类:
package com.java.protostuff.dyuproject;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
public class UserSerializationUtil {
private static RuntimeSchema<User> schema = RuntimeSchema.createFrom(User.class);
/**
* 序列化方法,将User对象序列化为字节数组
* @param user
* @return
*/
public static byte[] serialize(User user) {
return ProtostuffIOUtil.toByteArray(user, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
}
/**
* 反序列化方法,将字节数组反序列化为User对象
* @param array
* @return
*/
public static User deserialize(byte[] array) {
User user = schema.newMessage();
ProtostuffIOUtil.mergeFrom(array, user, schema);
return user;
}
}
测试类:
package com.java.protostuff.dyuproject;
public class Test {
public static void main(String[] args) {
// 创建User对象
User user = new User();
user.setName("dyuproject");
user.setAge(20);
System.out.println("序列化前:" + user);
// 使用UserSerializationUtil将user对象序列化
byte[] userBytes = UserSerializationUtil.serialize(user);
// 使用UserSerializationUtil反序列化字节数组为user对象
User user2 = UserSerializationUtil.deserialize(userBytes);
System.out.println("序列化后再反序列化:" + user2);
// 判断值是否相等
System.out.println(user.toString().equals(user2.toString()));
}
}
总结:protostuff比protobuf使用起来简单很多。
参考文档:https://code.google.com/archive/p/protostuff/
https://github.com/protostuff/protostuff
https://protostuff.github.io/docs/