Zookeeper 支援

4.2 版本為框架添加了 Zookeeper 支援,包括:

您需要在您的專案中包含此依賴項

  • Maven

  • Gradle

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

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 鎖登錄檔

在需要任何 LockRegistry 的地方都可以使用 ZookeeperLockRegistry,例如在叢集環境中使用聚合器和共享 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 的快取。有關更多資訊,請參閱其 JavaDoc。

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 選項會在內部建立一個 DefaultCandidate 例項,其 id 選項使用 UUID