Java - Protostuff 序列化和反序列化

序列化和反序列化是在應對網絡編程最常遇到的問題之一。

序列化就是將Java Object轉成byte[];反序列化就是將byte[]轉成Java Object。

這裏不介紹JDK Serializable的序列化方式,而是介紹一個更高效的序列化庫-Protostuff。

 

Protostuff 簡介

Protostuff的項目主頁:http://www.protostuff.io/

Protostuff 是一個序列化庫,支持一下序列化格式:

  • protobuf
  • protostuff(本地)
  • graph
  • json
  • smile
  • xml
  • yaml
  • kvp

 

序列化和反序列化工具

序列化

@SuppressWarnings("unchecked")
public static <T> byte[] serialize(T obj) {
    Class<T> cls = (Class<T>) obj.getClass();
    LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    try {
        Schema<T> schema = getSchema(cls);
        return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    } finally {
        buffer.clear();
    }
}

第3行:獲得對象的類;
第4行:使用LinkedBuffer分配一塊默認大小的buffer空間;
第6行:通過對象的類構建對應的schema;
第7行:使用給定的schema將對象序列化爲一個byte數組,並返回。

反序列化

public static <T> T deserialize(byte[] data, Class<T> cls) {
    try {
        T message = objenesis.newInstance(cls);
        Schema<T> schema = getSchema(cls);
        ProtostuffIOUtil.mergeFrom(data, message, schema);
        return message;
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

第3行:使用objenesis實例化一個類的對象;
第4行:通過對象的類構建對應的schema;
第5,6行:使用給定的schema將byte數組和對象合併,並返回。

 

構建 Schema

構建schema的過程可能會比較耗時,因此希望使用過的類對應的schema能被緩存起來。代碼如下,不再贅述:

private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

private static <T> Schema<T> getSchema(Class<T> cls) {
    Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
    if (schema == null) {
        schema = RuntimeSchema.createFrom(cls);
        if (schema != null) {
            cachedSchema.put(cls, schema);
        }
    }
    return schema;
}

可以看到方法第4行使用了RuntimeSchema,關於RuntimeSchema的用法,參考:// TODO

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章