介绍
在很多地方都需要用到序列化, 比如在使用redis缓存对象时, 一般情况是实现java Serializable接口. 简单介绍下在慕课网学习到的一个新的序列化工具 —- protostuff.
在学习中介绍使用该工具可以大大减少对象序列化后字节所占空间, 并提高序列化时间等.
1.慕课网课程地址
2.序列化相关工具比较
引入依赖
1 2 3 4 5 6 7 8 9 10 11
| <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>
|
相关使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import com.dyuproject.protostuff.LinkedBuffer; import com.dyuproject.protostuff.ProtostuffIOUtil; import com.dyuproject.protostuff.runtime.RuntimeSchema;
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; }
}
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import lombok.Data;
@Data public class User {
private String id;
private String userName;
}
import com.alibaba.fastjson.JSON;
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"}
|