google原生的protobuffer使用起来相当麻烦,首先要写.proto文件,然后编译.proto文件,生成对应的.java文件。
因此诞生了protostuff这个东西:http://www.protostuff.io/documentation/runtime-schema/
protostuff是一个基于protobuf实现的序列化方法,它较于protobuf最明显的好处是,在几乎不损耗性能的情况下做到了不用我们写.proto文件来实现序列化。使用它也非常简单,所以直接上代码。protostuff是一个基于protobuf实现的序列化方法,它较于protobuf最明显的好处是,在几乎不损耗性能的情况下做到了不用我们写.proto文件来实现序列化。
现在使用起来就比较简单了!
1.maven依赖:
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.4.0</version>
</dependency>
2.ProtoBufUtil工具类:ProtoBufUtil.java
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
public class ProtoBufUtil {
public static <T> byte[] serializer(T o) {
Schema schema = RuntimeSchema.getSchema(o.getClass());
return ProtostuffIOUtil.toByteArray(o, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
}
public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
Schema schema = RuntimeSchema.getSchema(clazz);
T obj = (T) schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes, obj, schema);
return obj;
}
}
3. bean类:
private static class User {
private String name;
private Integer age;
......
getter and setter ...
......
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("User{");
sb.append("name='").append(name).append('\'');
sb.append(", age=").append(age);
sb.append('}');
return sb.toString();
}
}
3.test类:
public class ProtoBufUtilTest {
public static void main(String[] args) {
User user = new User();
user.setAge(100);
user.setName("Admin");
byte[] bytes = ProtoBufUtil.serializer(user);
System.out.println(ProtoBufUtil.deserializer(bytes, User.class));
}
}