第 4 章 数据转换
Data Grid 使用 transcoders 在由介质类型识别的各种编码间转换数据。
4.1. hot Rod DataFormat API 复制链接链接已复制到粘贴板!
通过 Hot Rod 端点对远程缓存进行读写操作默认使用客户端 marshaller。热 Rod 为 Java 客户端提供了一个 DataFormat API,可用于使用不同的介质类型编码和/或 marshallers 执行缓存操作。
键和值的不同 marshallers
您可以在运行时覆盖键和值的 marshallers。
例如,要绕过 Hot Rod 客户端中的所有序列化,并读取远程缓存中存储的 byte[] 数组:
// Existing RemoteCache instance
RemoteCache<String, Pojo> remoteCache = ...
// IdentityMarshaller is a no-op marshaller
DataFormat rawKeyAndValues =
DataFormat.builder()
.keyMarshaller(IdentityMarshaller.INSTANCE)
.valueMarshaller(IdentityMarshaller.INSTANCE)
.build();
// Creates a new instance of RemoteCache with the supplied DataFormat
RemoteCache<byte[], byte[]> rawResultsCache =
remoteCache.withDataFormat(rawKeyAndValues);
对带有 keyMarshaller () 和 keyType () 方法的密钥使用不同的 marshallers 和数据格式可能会干扰客户端智能路由机制,从而导致 Data Grid 集群中的额外的网络跃点。如果性能至关重要,您应该对客户端和服务器上的密钥使用相同的编码。
读取不同编码中的数据
在 org.infinispan.commons.dataconversion.MediaType 指定的不同编码中请求并发送数据,如下所示:
// Existing remote cache using ProtostreamMarshaller
RemoteCache<String, Pojo> protobufCache = ...
// Request values returned as JSON
// Use the UTF8StringMarshaller to convert UTF-8 to String
DataFormat jsonString =
DataFormat.builder()
.valueType(MediaType.APPLICATION_JSON)
.valueMarshaller(new UTF8StringMarshaller())
.build();
RemoteCache<byte[], byte[]> rawResultsCache =
protobufCache.withDataFormat(jsonString);
使用自定义值 marshallers
您可以使用自定义 marshallers 作为值,如以下示例中返回值 org.codehaus.jackson.JsonNode 对象。
在本例中,Data Grid 服务器处理数据转换,并在不支持指定介质类型时抛出异常。
DataFormat jsonNode =
DataFormat.builder()
.valueType(MediaType.APPLICATION_JSON)
.valueMarshaller(new CustomJacksonMarshaller()
.build();
RemoteCache<String, JsonNode> jsonNodeCache =
remoteCache.withDataFormat(jsonNode);
返回值为 XML
以下代码片段返回值为 XML:
Object xmlValue = remoteCache
.withDataFormat(DataFormat.builder()
.valueType(MediaType.APPLICATION_XML)
.valueMarshaller(new UTF8StringMarshaller())
.build())
.get(key);
例如,前面的 get (key) 调用返回值,例如:
<?xml version="1.0" ?><string>Hello!</string>