Zookeeper 支援

版本 4.2 在版本 4.2 中為框架新增了 Zookeeper 支援,其中包括

您需要將此相依性包含到您的專案中

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-zookeeper</artifactId>
    <version>6.3.5</version>
</dependency>
compile "org.springframework.integration:spring-integration-zookeeper:6.3.5"

Zookeeper 中繼資料儲存

您可以在任何需要 MetadataStore 的地方使用 ZookeeperMetadataStore,例如用於持久檔案清單篩選器。有關更多資訊,請參閱 中繼資料儲存。以下範例使用 XML 設定 Zookeeper 中繼資料儲存

<bean id="client" class="org.springframework.integration.zookeeper.config.CuratorFrameworkFactoryBean">
    <constructor-arg value="${connect.string}" />
</bean>

<bean id="meta" class="org.springframework.integration.zookeeper.metadata.ZookeeperMetadataStore">
    <constructor-arg ref="client" />
</bean>

以下範例示範如何使用 Java 設定 Zookeeper 中繼資料儲存

@Bean
public MetadataStore zkStore(CuratorFramework client) {
    return new ZookeeperMetadataStore(client);
}

Zookeeper 鎖定登錄

ZookeeperLockRegistry 可用於任何需要 LockRegistry 的地方,例如在叢集環境中使用具有共用 MessageStore 的彙集器時。

LockRegistry 用於根據金鑰「查找」鎖定 (彙集器使用 correlationId)。預設情況下,ZookeeperLockRegistry 中的鎖定維護在 zookeeper 中,路徑如下:/SpringIntegration-LockRegistry/。您可以透過提供 ZookeeperLockRegistry.KeyToPathStrategy 的實作來自訂路徑,如下列範例所示

public interface KeyToPathStrategy {

    String pathFor(String key);

    boolean bounded();

}

如果策略從 isBounded 傳回 true,則不需要收集未使用的鎖定。對於無界限策略 (例如預設策略),您需要定期調用 expireUnusedOlderThan(long age) 以從記憶體中移除舊的未使用鎖定。

從 5.5.6 版開始,ZookeeperLockRegistry 支援透過 ZookeeperLockRegistry.setCacheCapacity() 自動清理 ZookeeperLockRegistry.locks 中 ZkLock 的快取。有關更多資訊,請參閱其 JavaDocs。

Zookeeper 領導權事件處理

以下範例使用 XML 設定應用程式以在 Zookeeper 中進行領導者選舉

<int-zk:leader-listener client="client" path="/siNamespace" role="cluster" />

client 是對 CuratorFramework bean 的參考。CuratorFrameworkFactoryBean 可用。當選出領導者時,會為角色 cluster 發布 OnGrantedEvent。該角色中的任何端點都會啟動。當領導權被撤銷時,會為角色 cluster 發布 OnRevokedEvent。該角色中的任何端點都會停止。有關更多資訊,請參閱 端點角色

您可以使用 Java 設定來建立領導者啟動器的實例,如下列範例所示

@Bean
public LeaderInitiatorFactoryBean leaderInitiator(CuratorFramework client) {
    return new LeaderInitiatorFactoryBean()
                .setClient(client)
                .setPath("/siTest/")
                .setRole("cluster");
}

從 5.3 版開始,LeaderInitiatorFactoryBean 上公開了 candidate 選項,以便對外部提供的 Candidate 實例進行更多設定控制。candidaterole 選項只需提供其中一個,但不能同時提供;role 選項會在內部建立具有 UUID 作為 id 選項的 DefaultCandidate 實例。