我們在使用 MessagePack 對 List 對象數據進行序列化的時候,發現序列化以後的二進制數組數據偏大的情況。
請注意,不是所有的 List 對象都會出現這種情況,這個根據你 List 對象中存儲的內容有關。
有關本問題的測試源代碼請參考:https://github.com/cwiki-us-demo/serialize-deserialize-demo-java/blob/master/src/test/java/com/insight/demo/serialize/MessagePackDataTest.java 中的內容。
考察下面的代碼:
List<MessageData> dataList = MockDataUtils.getMessageDataList(600000);
ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
raw = objectMapper.writeValueAsBytes(dataList);
FileUtils.byteCountToDisplaySize(raw.length);
logger.debug("Raw Size: [{}]", FileUtils.byteCountToDisplaySize(raw.length));
我們會發現,針對這個 60 萬個對象的 List 的序列化後的數據達到了 33MB。
如果我們再定義 ObjectMapper 對象的時候添加一部分參數,我們會發現大小將會有顯著改善。
請參考下面的代碼:
List<MessageData> dataList = MockDataUtils.getMessageDataList(600000);
ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setAnnotationIntrospector(new JsonArrayFormat());
rawJsonArray = objectMapper.writeValueAsBytes(dataList);
logger.debug("rawJsonArray Size: [{}]", FileUtils.byteCountToDisplaySize(rawJsonArray.length));
如果你運行上面的代碼,你會看到程序的輸出字符串將會降低到 23MB。
這裏面主要是 objectMapper.setAnnotationIntrospector(new JsonArrayFormat()); 這句話起了作用。
在正常的場景中,我們可以通過 註解 JsonIgnore, 將其加到屬性上,即解析時即會過濾到屬性。
而實際實現,則是由類 JacksonAnnotationIntrospector 中 的 hasIgnoreMarker 來完成,則就是通過讀取註解來判斷屬性是否應該被exclude掉。ObjectMapper中默認的 AnnotationIntrospector 即是 JacksonAnnotationIntrospector 來完成,但我們可以通過 方法 ObjectMapper.setAnnotationIntrospector 來重新指定自定義的實現。
https://www.cwiki.us/display/Serialization/MessagePack+Jackson+Data+Size