我计划在我们的项目中使用Messagepack。目前,我们正在项目中使用JSON,我们正在将序列化JSON文档写入Cassandra。现在我们正在考虑使用消息包,这是一种有效的二进制序列化格式。
我正在尝试找到一个很好的例子,它显示我在 JSON 文档上使用消息包,但我还找不到它。
下面是我的主要类代码,它将使用Value class使用Jackson制作JSON文档,然后使用ObjectMapper序列化JSON。
public static void main(String[] args) {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("id", 123);
properties.put("test", 200);
properties.put("marks", 100);
Value val = new Value();
val.setProperties(properties);
MessagePack msgpack = new MessagePack();
// Serialize
byte[] raw = msgpack.write(av);
System.out.println(raw);
// deserialize
Value actual = new MessagePack().read(raw, Value.class);
System.out.println(actual);
}
下面是我的 Value 类,它使用 Jackson 制作 JSON 文档,并将使用 ObjectMapper 来序列化文档,并使用 Messagepack。
@JsonPropertyOrder(value = { "v" })
@Message
public class Value {
private Map<String, Object> properties;
/**
* Default constructor.
*/
@JsonCreator
public Value() {
properties = new HashMap<String, Object>();
}
/**
* Gets the properties of this attribute value.
* @return the properties of this attribute value.
*/
@JsonProperty("v")
public Map<String, Object> getProperties() {
return properties;
}
/**
* Sets the properties of this attribute value.
* @param v the properties of this attribute value to set
*/
@JsonProperty("v")
public void setProperties(Map<String, Object> v) {
properties = v;
}
@Override
public String toString() {
try {
return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (Exception e) {
// log exception
}
return ToStringBuilder.reflectionToString(this);
}
}
但是,我不确定如何在此JSON文档上使用消息包?谁能给我举一些例子?
但是我想,让我们尝试一下,每当我尝试在上面的代码中使用这样的 Messagepack 时-
MessagePack msgpack = new MessagePack();
// Serialize
byte[] raw = msgpack.write(av);
我总是得到如下的例外——
Exception in thread "main" org.msgpack.MessageTypeException: Cannot find template for class java.lang.Object class. Try to add @Message annotation to the class or call MessagePack.register(Type).
我相信MessagePack不允许用户序列化java.lang.Object类型的变量,但就我而言,不可能将属性类型替换为某些原始类型。
我在我的哈希图中使用对象,我需要它像那样。
与其尝试MessagePack
,您是否考虑过使用 Smile,这是一种高效的、100% JSON API 兼容的二进制数据格式。它应该匹配或超过MessagePack
速度,并产生稍微紧凑的输出。杰克逊在以下方面实施:
https://github.com/FasterXML/jackson-dataformat-smile
这将"只适用于"对象格式。所以代替:
String json = new ObjectMapper().writeValueAsString(value);
你会使用
byte[] smileEncoded = new ObjectMapper(new SmileFactory()).writeValueAsBytes(value);
所有 Jackson 代码的工作方式都类似于 JSON,包括 JAX-RS 提供程序、数据类型(Guava、Joda、Hibernate 等)等。因此,您不会失去JSON的便利性(除了像所有二进制格式一样,Smile不如JSON可读),而是获得存储和性能效率。