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);
Copy to Clipboard Toggle word wrap
重要

对键使用不同的 marshallers 和格式,keyMarshaller ()keyType () 方法可能会影响客户端智能路由机制,并导致 Data Grid 集群中的额外跃点执行该操作。如果性能至关重要,您应该使用服务器存储的格式的密钥。

返回 XML 值

Object xmlValue = remoteCache
      .withDataFormat(DataFormat.builder()
      .valueType(APPLICATION_XML)
      .valueMarshaller(new UTF8StringMarshaller())
      .build())
      .get(key);
Copy to Clipboard Toggle word wrap

前面的代码示例返回 XML 值,如下所示:

<?xml version="1.0" ?><string>Hello!</string>
Copy to Clipboard Toggle word wrap

以不同格式读取数据

请求并发送由 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);
Copy to Clipboard Toggle word wrap
// 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);
Copy to Clipboard Toggle word wrap

在上例中,数据转换发生在 Data Grid 服务器中。如果数据源不支持从存储格式进行转换,则数据网格会抛出异常。

返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat