이 콘텐츠는 선택한 언어로 제공되지 않습니다.
Chapter 2. Configuring Hot Rod Java Clients
2.1. Programmatically Configuring Hot Rod Java Clients 링크 복사링크가 클립보드에 복사되었습니다!
Use the ConfigurationBuilder class to generate immutable configuration objects that you can pass to RemoteCacheManager.
For example, create a client instance with the Java fluent API as follows:
2.2. Configuring Hot Rod Java Client Property Files 링크 복사링크가 클립보드에 복사되었습니다!
Add hotrod-client.properties to your classpath so that the client passes configuration to RemoteCacheManager.
Example hotrod-client.properties
To use hotrod-client.properties somewhere other than your classpath, do:
2.3. Client Intelligence 링크 복사링크가 클립보드에 복사되었습니다!
Hot Rod client intelligence refers to mechanisms for locating Data Grid servers to efficiently route requests.
Basic intelligence
Clients do not store any information about Data Grid clusters or key hash values.
Topology-aware
Clients receive and store information about Data Grid clusters. Clients maintain an internal mapping of the cluster topology that changes whenever servers join or leave clusters.
To receive a cluster topology, clients need the address (IP:HOST) of at least one Hot Rod server at startup. After the client connects to the server, Data Grid transmits the topology to the client. When servers join or leave the cluster, Data Grid transmits an updated topology to the client.
Distribution-aware
Clients are topology-aware and store consistent hash values for keys.
For example, take a put(k,v) operation. The client calculates the hash value for the key so it can locate the exact server on which the data resides. Clients can then connect directly to the owner to dispatch the operation.
The benefit of distribution-aware intelligence is that Data Grid servers do not need to look up values based on key hashes, which uses less resources on the server side. Another benefit is that servers respond to client requests more quickly because it skips additional network roundtrips.
2.3.1. Request Balancing 링크 복사링크가 클립보드에 복사되었습니다!
Clients that use topology-aware intelligence use request balancing for all requests. The default balancing strategy is round-robin, so topology-aware clients always send requests to servers in round-robin order.
For example, s1, s2, s3 are servers in a Data Grid cluster. Clients perform request balancing as follows:
Clients that use distribution-aware intelligence use request balancing only for failed requests. When requests fail, distribution-aware clients retry the request on the next available server.
Custom balancing policies
You can implement FailoverRequestBalancingStrategy and specify your class in your hotrod-client.properties configuration with the following property:
infinispan.client.hotrod.request_balancing_strategy
2.3.2. Client Failover 링크 복사링크가 클립보드에 복사되었습니다!
Hot Rod clients can automatically failover when Data Grid cluster topologies change. For instance, Hot Rod clients that are topology-aware can detect when one or more Data Grid servers fail.
In addition to failover between clustered Data Grid servers, Hot Rod clients can failover between Data Grid clusters.
For example, you have a Data Grid cluster running in New York (NYC) and another cluster running in London (LON). Clients sending requests to NYC detect that no nodes are available so they switch to the cluster in LON. Clients then maintain connections to LON until you manually switch clusters or failover happens again.
Transactional Caches with Failover
Conditional operations, such as putIfAbsent(), replace(), remove(), have strict method return guarantees. Likewise, some operations can require previous values to be returned.
Even though Hot Rod clients can failover, you should use transactional caches to ensure that operations do not partially complete and leave conflicting entries on different nodes.
2.4. Configuring Authentication Mechanisms for Hot Rod Clients 링크 복사링크가 클립보드에 복사되었습니다!
Data Grid servers use different mechanisms to authenticate Hot Rod client connections.
Procedure
-
Specify the authentication mechanisms that Data Grid server uses with the
saslMechanism()method from theSecurityConfigurationBuilderclass.
SCRAM
DIGEST
PLAIN
OAUTHBEARER
OAUTHBEARER authentication with TokenCallbackHandler
You can configure clients with a TokenCallbackHandler to refresh OAuth2 tokens before they expire, as in the following example:
EXTERNAL
GSSAPI
The preceding configuration uses the BasicCallbackHandler to retrieve the client subject and handle authentication. However, this actually invokes different callbacks:
-
NameCallbackandPasswordCallbackconstruct the client subject. -
AuthorizeCallbackis called during SASL authentication.
Custom CallbackHandler
Hot Rod clients set up a default CallbackHandler to pass credentials to SASL mechanisms. In some cases, you might need to provide a custom CallbackHandler.
Your CallbackHandler needs to handle callbacks that are specific to the authentication mechanism that you use. However, it is beyond the scope of this document to provide examples for each possible callback type.
2.4.1. Hot Rod Endpoint Authentication Mechanisms 링크 복사링크가 클립보드에 복사되었습니다!
Data Grid supports the following SASL authentications mechanisms with the Hot Rod connector:
| Authentication mechanism | Description | Related details |
|---|---|---|
|
|
Uses credentials in plain-text format. You should use |
Similar to the |
|
|
Uses hashing algorithms and nonce values. Hot Rod connectors support |
Similar to the |
|
|
Uses salt values in addition to hashing algorithms and nonce values. Hot Rod connectors support |
Similar to the |
|
|
Uses Kerberos tickets and requires a Kerberos Domain Controller. You must add a corresponding |
Similar to the |
|
|
Uses Kerberos tickets and requires a Kerberos Domain Controller. You must add a corresponding |
Similar to the |
|
| Uses client certificates. |
Similar to the |
|
|
Uses OAuth tokens and requires a |
Similar to the |
2.4.2. Creating GSSAPI Login Contexts 링크 복사링크가 클립보드에 복사되었습니다!
To use the GSSAPI mechanism, you must create a LoginContext so your Hot Rod client can obtain a Ticket Granting Ticket (TGT).
Procedure
Define a login module in a login configuration file.
gss.conf
GssExample { com.sun.security.auth.module.Krb5LoginModule required client=TRUE; };GssExample { com.sun.security.auth.module.Krb5LoginModule required client=TRUE; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow For the IBM JDK:
gss-ibm.conf
GssExample { com.ibm.security.auth.module.Krb5LoginModule required client=TRUE; };GssExample { com.ibm.security.auth.module.Krb5LoginModule required client=TRUE; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set the following system properties:
java.security.auth.login.config=gss.conf java.security.krb5.conf=/etc/krb5.conf
java.security.auth.login.config=gss.conf java.security.krb5.conf=/etc/krb5.confCopy to Clipboard Copied! Toggle word wrap Toggle overflow Notekrb5.confprovides the location of your KDC. Use the kinit command to authenticate with Kerberos and verifykrb5.conf.
2.5. Configuring Hot Rod Client Encryption 링크 복사링크가 클립보드에 복사되었습니다!
Data Grid servers that use SSL/TLS encryption present Hot Rod clients with certificates so they can establish trust and negotiate secure connections.
To verify server-issued certificates, Hot Rod clients require part of the TLS certificate chain. For example, the following image shows a certificate authority (CA), named "CA", that has issued a certificate for a server named "HotRodServer":
Figure 2.1. Certificate chain
Procedure
- Create a Java keystore with part of the server certificate chain. In most cases you should use the public certificate for the CA.
-
Specify the keystore as a TrustStore in the client configuration with the
SslConfigurationBuilderclass.
Specify a path that contains certificates in PEM format and Hot Rod clients automatically generate trust stores.
Use .trustStorePath("/path/to/certificate").
2.6. Monitoring Hot Rod Client Statistics 링크 복사링크가 클립보드에 복사되었습니다!
Enable Hot Rod client statistics that include remote and near-cache hits and misses as well as connection pool usage.
Procedure
-
Use the
StatisticsConfigurationBuilderclass to enable and configure Hot Rod client statistics.
2.7. Defining Data Grid Clusters in Client Configuration 링크 복사링크가 클립보드에 복사되었습니다!
Provide the locations of Data Grid clusters in Hot Rod client configuration.
Procedure
Provide at least one Data Grid cluster name, hostname, and port with the
ClusterConfigurationBuilderclass.Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Default Cluster
When adding clusters to your Hot Rod client configuration, you can define a list of Data Grid servers in the format of hostname1:port; hostname2:port. Data Grid then uses the server list as the default cluster configuration.
2.7.1. Manually Switching Data Grid Clusters 링크 복사링크가 클립보드에 복사되었습니다!
Manually switch Hot Rod Java client connections between Data Grid clusters.
Procedure
Call one of the following methods in the
RemoteCacheManagerclass:switchToCluster(clusterName)switches to a specific cluster defined in the client configuration.switchToDefaultCluster()switches to the default cluster in the client configuration, which is defined as a list of Data Grid servers.
Reference
2.8. Creating Caches with Hot Rod Clients 링크 복사링크가 클립보드에 복사되었습니다!
Programmatically create caches on Data Grid Server through the RemoteCacheManager API.
The following procedure demonstrates programmatic cache creation with the Hot Rod Java client. However Hot Rod clients are available in different languages such as Javascript or C++.
Prerequisites
- Create a user and start at least one Data Grid server instance.
- Get the Hot Rod Java client.
Procedure
Configure your client with the
ConfigurationBuilderclass.Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
Use the
XMLStringConfigurationclass to add cache definitions in XML format. Call the
getOrCreateCache()method to add the cache if it already exists or create it if not.Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create caches with
org.infinispantemplates as in the following example with thecreateCache()invocation:private void createCacheWithTemplate() { manager.administration().createCache("myCache", "org.infinispan.DIST_SYNC"); System.out.println("Cache created."); }private void createCacheWithTemplate() { manager.administration().createCache("myCache", "org.infinispan.DIST_SYNC"); System.out.println("Cache created."); }Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Next Steps
Try some working code examples that show you how to create remote caches with the Hot Rod Java client. Visit the Data Grid Tutorials.
2.9. Creating Caches on First Access 링크 복사링크가 클립보드에 복사되었습니다!
When Hot Rod Java clients attempt to access caches that do not exist, they return null for getCache("$cacheName") invocations.
You can change this default behavior so that clients automatically create caches on first access using default configuration templates or Data Grid cache definitions in XML format.
Programmatic procedure
-
Use the
remoteCache()method to create per-cache configurations in the Hot RodConfigurationBuilderclass as follows:
Hot Rod client properties
-
Add
infinispan.client.hotrod.cache.<cache-name>properties to yourhotrod-client.propertiesfile to create per-cache configurations as follows:
infinispan.client.hotrod.cache.my-cache.template_name=org.infinispan.DIST_SYNC infinispan.client.hotrod.cache.another-cache.configuration=<infinispan><cache-container><distributed-cache name=\"another-cache\"/></cache-container></infinispan> infinispan.client.hotrod.cache.my-other-cache.configuration_uri=file:/path/to/configuration.xml
infinispan.client.hotrod.cache.my-cache.template_name=org.infinispan.DIST_SYNC
infinispan.client.hotrod.cache.another-cache.configuration=<infinispan><cache-container><distributed-cache name=\"another-cache\"/></cache-container></infinispan>
infinispan.client.hotrod.cache.my-other-cache.configuration_uri=file:/path/to/configuration.xml
2.10. Creating Per-Cache Configurations 링크 복사링크가 클립보드에 복사되었습니다!
In addition to creating caches on first access, you can remotely configure certain aspects of individual caches such as:
- Force return values
- Near-caching
- Transaction modes
Procedure
-
Enable force return values for a cache named
a-cacheas follows:
-
Use wildcard globbing in the remote cache name to enable force return values for all caches that start with the string
somecaches:
When using declarative configuration and your cache names contain the . character, you must enclose the cache name in square brackets, for example infinispan.client.hotrod.cache.[example.MyCache].template=…
2.11. Configuring Near Caching 링크 복사링크가 클립보드에 복사되었습니다!
Hot Rod Java clients can keep local caches that store recently used data, which significantly increases performance of get() and getVersioned() operations because the data is local to the client.
When you enable near caching with Hot Rod Java clients, calls to get() or getVersioned() calls populate the near cache when entries are retrieved from servers. When entries are updated or removed on the server-side, entries in the near cache are invalidated. If keys are requested after they are invalidated, clients must fetch the keys from the server again.
You can also configure the number of entries that near caches can contain. When the maximum is reached, near-cached entries are evicted.
Do not use maximum idle expiration with near caches because near-cache reads do not propagate the last access time for entries.
- Near caches are cleared when clients failover to different servers when using clustered cache modes.
- You should always configure the maximum number of entries that can reside in the near cache. Unbounded near caches require you to keep the size of the near cache within the boundaries of the client JVM.
- Near cache invalidation messages can degrade performance of write operations
Procedure
-
Set the near cache mode to
INVALIDATEDin the client configuration for the caches you want - Define the size of the near cache by specifying the maximum number of entries.
You should always configure near caching on a per-cache basis. Even though Data Grid provides global near cache configuration properties, you should not use them.
2.12. Forcing Return Values 링크 복사링크가 클립보드에 복사되었습니다!
To avoid sending data unnecessarily, write operations on remote caches return null instead of previous values.
For example, the following method calls do not return previous values for keys:
V remove(Object key); V put(K key, V value);
V remove(Object key);
V put(K key, V value);
You can change this default behavior with the FORCE_RETURN_VALUE flag so your invocations return previous values.
Procedure
-
Use the
FORCE_RETURN_VALUEflag to get previous values instead ofnullas in the following example:
cache.put("aKey", "initialValue");
assert null == cache.put("aKey", "aValue");
assert "aValue".equals(cache.withFlags(Flag.FORCE_RETURN_VALUE).put("aKey",
"newValue"));
cache.put("aKey", "initialValue");
assert null == cache.put("aKey", "aValue");
assert "aValue".equals(cache.withFlags(Flag.FORCE_RETURN_VALUE).put("aKey",
"newValue"));
Reference
2.13. Configuring Connection Pools 링크 복사링크가 클립보드에 복사되었습니다!
Hot Rod Java clients keep pools of persistent connections to Data Grid servers to reuse TCP connections instead of creating them on each request.
Clients use asynchronous threads that check the validity of connections by iterating over the connection pool and sending pings to Data Grid servers. This improves performance by finding broken connections while they are idle in the pool, rather than on application requests.
Procedure
-
Configure Hot Rod client connection pool settings with the
ConnectionPoolConfigurationBuilderclass.
2.14. Hot Rod Java Client Marshalling 링크 복사링크가 클립보드에 복사되었습니다!
Hot Rod is a binary TCP protocol that requires you to transform Java objects into binary format so they can be transferred over the wire or stored to disk.
By default, Data Grid uses a ProtoStream API to encode and decode Java objects into Protocol Buffers (Protobuf); a language-neutral, backwards compatible format. However, you can also implement and use custom marshallers.
2.14.1. Configuring SerializationContextInitializer Implementations 링크 복사링크가 클립보드에 복사되었습니다!
You can add implementations of the ProtoStream SerializationContextInitializer interface to Hot Rod client configurations so Data Grid marshalls custom Java objects.
Procedure
-
Add your
SerializationContextInitializerimplementations to your Hot Rod client configuration as follows:
hotrod-client.properties
infinispan.client.hotrod.context-initializers=org.infinispan.example.LibraryInitializerImpl,org.infinispan.example.AnotherExampleSciImpl
infinispan.client.hotrod.context-initializers=org.infinispan.example.LibraryInitializerImpl,org.infinispan.example.AnotherExampleSciImpl
Programmatic configuration
2.14.2. Configuring Custom Marshallers 링크 복사링크가 클립보드에 복사되었습니다!
Configure Hot Rod clients to use custom marshallers.
Procedure
-
Implement the
org.infinispan.commons.marshall.Marshallerinterface. - Specify the fully qualified name of your class in your Hot Rod client configuration.
Add your Java classes to the Data Grid deserialization whitelist.
In the following example, only classes with fully qualified names that contain
PersonorEmployeeare allowed:ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder.marshaller("org.infinispan.example.marshall.CustomMarshaller") .addJavaSerialWhiteList(".*Person.*", ".*Employee.*"); ...ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder.marshaller("org.infinispan.example.marshall.CustomMarshaller") .addJavaSerialWhiteList(".*Person.*", ".*Employee.*"); ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow
2.15. Configuring Hot Rod Client Data Formats 링크 복사링크가 클립보드에 복사되었습니다!
By default, Hot Rod client operations use the configured marshaller when reading and writing from Data Grid servers for both keys and values.
However, the DataFormat API lets you decorate remote caches so that all operations can happen with custom data formats.
Using different marshallers for key and values
Marshallers for keys and values can be overridden at run time. For example, to bypass all serialization in the Hot Rod client and read the byte[] as they are stored in the server:
Using different marshallers and formats for keys, with keyMarshaller() and keyType() methods might interfere with the client intelligence routing mechanism and cause extra hops within the Data Grid cluster to perform the operation. If performance is critical, you should use keys in the format stored by the server.
Returning XML Values
The preceding code example returns XML values as follows:
<?xml version="1.0" ?><string>Hello!</string>
<?xml version="1.0" ?><string>Hello!</string>
Reading data in different formats
Request and send data in different formats specified by a org.infinispan.commons.dataconversion.MediaType as follows:
In the preceding example, data conversion happens in the Data Grid server. Data Grid throws an exception if it does not support conversion to and from a storage format.
Reference