11.5. 使用 Hot Rod 客户端创建远程缓存

当 Hot Rod Java 客户端试图访问不存在的缓存时,它们会返回 remoteCacheManager.getCache ("myCache") 调用的 null。为避免这种情况,您可以将 Hot Rod 客户端配置为使用缓存配置在首次访问时创建缓存。

流程

  • 使用 ConfigurationBuilder 中的 remoteCache () 方法,或者使用 hotrod-client.properties 中的 configurationconfiguration_uri 属性。

ConfigurationBuilder

File file = new File("path/to/infinispan.xml")
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.remoteCache("another-cache")
       .configuration("<distributed-cache name=\"another-cache\"/>");
builder.remoteCache("my.other.cache")
       .configurationURI(file.toURI());

hotrod-client.properties

infinispan.client.hotrod.cache.another-cache.configuration=<distributed-cache name=\"another-cache\"/>
infinispan.client.hotrod.cache.[my.other.cache].configuration_uri=file:///path/to/infinispan.xml

重要

hotrod-client.properties 与包含 . 字符的缓存名称一起使用时,您必须将缓存名称放在方括号中,如上例中所示。

您还可以以其他方式通过 RemoteCacheManager API 创建远程缓存,例如以下示例使用 XMLStringConfiguration () 方法添加缓存配置,然后调用 getOrCreateCache () 方法。

但是,Data Grid 不推荐使用这个方法,因为它可能更难以确保 XML 的有效性,通常更难以创建缓存。如果您要创建复杂的缓存配置,您应该将它们保存到项目中的单独文件中,并在 Hot Rod 客户端配置中引用它们。

String cacheName = "CacheWithXMLConfiguration";
String xml = String.format("<distributed-cache name=\"%s\" mode=\"SYNC\">" +
                              "<encoding media-type=\"application/x-protostream\"/>" +
                              "<locking isolation=\"READ_COMMITTED\"/>" +
                              "<transaction mode=\"NON_XA\"/>" +
                              "<expiration lifespan=\"60000\" interval=\"20000\"/>" +
                           "</distributed-cache>" , cacheName);
remoteCacheManager.administration().getOrCreateCache(cacheName, new XMLStringConfiguration(xml));

热 Rod 代码示例

尝试一些数据网格代码教程,其中向您展示如何使用 Hot Rod Java 客户端以不同的方式创建远程缓存。

访问 Data Grid 代码示例