2.2.6. 关键关联性服务

在分布式缓存中,密钥被分配到一个带有不透明算法的节点列表。无法轻松撤销计算并生成映射到特定节点的键。但是,数据网格可生成一系列(伪)随机键,查看其主所有者是哪一个,并在需要密钥映射到特定节点时将其转移到应用程序。

以下代码片段描述了如何获取和使用该服务。

// 1. Obtain a reference to a cache
Cache cache = ...
Address address = cache.getCacheManager().getAddress();

// 2. Create the affinity service
KeyAffinityService keyAffinityService = KeyAffinityServiceFactory.newLocalKeyAffinityService(
      cache,
      new RndKeyGenerator(),
      Executors.newSingleThreadExecutor(),
      100);

// 3. Obtain a key for which the local node is the primary owner
Object localKey = keyAffinityService.getKeyForAddress(address);

// 4. Insert the key in the cache
cache.put(localKey, "yourValue");

服务从第 2 步启动:此时使用提供的 Executor 生成和队列键。在第 3 步中,我们从服务中获取密钥,并在第 4 步中使用它。

生命周期

KeyAffinityService 扩展 生命周期,允许停止和(重新)启动它:

public interface Lifecycle {
   void start();
   void stop();
}

该服务通过 KeyAffinityServiceFactory 进行实例化。所有工厂方法都有 Executor 参数,该参数用于异步密钥生成(因此它不会在调用者的线程中发生)。用户负责处理此可执行文件的关闭

启动后,需要显式停止 KeyAffinityService。这会停止后台密钥生成并释放其他保存的资源。

唯一停止的 KeyAffinityService 才会在关闭了它注册的缓存管理器时。

拓扑更改

当缓存拓扑更改时,KeyAffinityService 生成的密钥所有权可能会改变。关键关联性服务会跟踪这些拓扑的更改,且不会返回当前映射到不同节点的键,但它不会执行之前生成的密钥。

因此,应用程序应该完全将 KeyAffinityService 视为优化,它们不应依赖于生成的密钥的位置来获得正确性。

特别是,应用程序不应该依赖 KeyAffinityService 生成的密钥来始终放在一起。密钥的并置仅由组 API 提供