Ce contenu n'est pas disponible dans la langue sélectionnée.
28.5. Key Affinity Service
Example 28.2. Key Affinity Service
EmbeddedCacheManager cacheManager = getCacheManager();
Cache cache = cacheManager.getCache();
KeyAffinityService keyAffinityService =
KeyAffinityServiceFactory.newLocalKeyAffinityService(
cache,
new RndKeyGenerator(),
Executors.newSingleThreadExecutor(),
100);
Object localKey = keyAffinityService.getKeyForAddress(cacheManager.getAddress());
cache.put(localKey, "yourValue");
Procedure 28.3. Using the Key Affinity Service
Obtain a reference to a cache manager and cache
EmbeddedCacheManager cacheManager = getCacheManager(); Cache cache = cacheManager.getCache();Create the affinity service
This starts the service, then uses the suppliedExecutorto generate and queue keys.KeyAffinityService keyAffinityService = KeyAffinityServiceFactory.newLocalKeyAffinityService( cache, new RndKeyGenerator(), Executors.newSingleThreadExecutor(), 100);Obtain a key to be mapped to a certain address
Obtain a key from the service which will be mapped to the local node (cacheManager.getAddress()returns the local address).Object localKey = keyAffinityService.getKeyForAddress(cacheManager.getAddress());Put the value on the node
The entry with a key obtained from theKeyAffinityServiceis always stored on the node with the provided address. In this case, it is the local node.cache.put(localKey, "yourValue");
28.5.1. Lifecycle Copier lienLien copié sur presse-papiers!
KeyAffinityService extends Lifecycle, which allows the key affinity service to be stopped, started, and restarted.
Example 28.3. Key Affinity Service Lifecycle Parameter
public interface Lifecycle {
void start();
void stop();
}
KeyAffinityServiceFactory. All factory methods have an Executor, that is used for asynchronous key generation, so that this does not occur in the caller's thread. The user controls the shutting down of this Executor.
KeyAffinityService must be explicitly stopped when it is no longer required. This stops the background key generation, and releases other held resources. The KeyAffinityServce will only stop itself when the cache manager with which it is registered is shut down.
28.5.2. Topology Changes Copier lienLien copié sur presse-papiers!
KeyAffinityService key ownership may change when a topology change occurs. The key affinity service monitors topology changes and updates so that it doesn't return stale keys, or keys that would map to a different node than the one specified. However, this does not guarantee that a node affinity hasn't changed when a key is used. For example:
- Thread (
T1) reads a key (K1) that maps to a node (A). - A topology change occurs, resulting in
K1mapping to nodeB. T1usesK1to add something to the cache. At this point,K1maps toB, a different node to the one requested at the time of read.
KeyAffinityService provides an access proximity optimization for stable clusters, which does not apply during the instability of topology changes.