2.15. 配置 Hot Rod 客户端数据格式
默认情况下,Hot Rod 客户端操作在读取和写入 Data Grid 服务器时使用配置的 marshaller。
但是,DataFormat API 允许您分离远程缓存,以便所有操作都可以使用自定义数据格式发生。
将不同的 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);
重要
对键使用不同的 marshallers 和格式,keyMarshaller () 和 keyType () 方法可能会影响客户端智能路由机制,并导致 Data Grid 集群中的额外跃点执行该操作。如果性能至关重要,您应该使用服务器存储的格式的密钥。
返回 XML 值
Object xmlValue = remoteCache
.withDataFormat(DataFormat.builder()
.valueType(APPLICATION_XML)
.valueMarshaller(new UTF8StringMarshaller())
.build())
.get(key);
前面的代码示例返回 XML 值,如下所示:
<?xml version="1.0" ?><string>Hello!</string>
以不同格式读取数据
请求并发送由 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);
// Alternatively, use a custom value marshaller
// that returns `org.codehaus.jackson.JsonNode` objects
DataFormat jsonNode =
DataFormat.builder()
.valueType(MediaType.APPLICATION_JSON)
.valueMarshaller(new CustomJacksonMarshaller()
.build();
RemoteCache<String, JsonNode> jsonNodeCache =
remoteCache.withDataFormat(jsonNode);
在上例中,数据转换发生在 Data Grid 服务器中。如果数据源不支持从存储格式进行转换,则数据网格会抛出异常。