搜索

第 4 章 数据转换

download PDF

Data Grid 使用 transcoders 在由介质类型标识的不同编码之间转换数据。

4.1. hot Rod DataFormat API

通过 Hot Rod 端点对远程缓存的读写操作默认使用客户端 marshaller。热 Rod 为 Java 客户端提供 DataFormat API,您可以使用它来执行具有不同介质类型 encodings 和/或 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>
Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

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

让开源更具包容性

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

關於紅帽

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

© 2024 Red Hat, Inc.