Zookeeper 支援
4.2 版本為框架增加了 Zookeeper 支援,包括
專案需要此依賴項
-
Maven
-
Gradle
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-zookeeper</artifactId>
<version>7.0.0</version>
</dependency>
compile "org.springframework.integration:spring-integration-zookeeper:7.0.0"
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 例項。candidate 或 role 選項只需提供其中一個,但不能同時提供;role 選項會在內部建立一個 DefaultCandidate 例項,其中 id 選項為 UUID。