跳到主要内容

Zookeeper 支持

QWen Plus 中英对照 Zookeeper Support

版本 4.2 在框架中添加了 Zookeeper 支持,其内容包括:

你需要将这个依赖项添加到你的项目中:

<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-zookeeper</artifactId>
<version>6.4.2</version>
</dependency>
xml

Zookeeper 元数据存储

你可以在任何需要 MetadataStore 的地方使用 ZookeeperMetadataStore,例如用于持久化文件列表过滤器。更多信息请参见 Metadata Store。以下示例使用 XML 配置了一个 Zookeeper 元数据存储:

<zookeeper-metadata-store>
<!-- Configuration details -->
</zookeeper-metadata-store>
xml

请注意,上述 XML 代码中的配置细节需要根据实际情况进行设置。

<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>
xml

以下示例展示了如何使用 Java 配置 Zookeeper 元数据存储:

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

Zookeeper 锁注册表

ZookeeperLockRegistry 可以在任何需要 LockRegistry 的地方使用,例如在集群环境中使用聚合器和共享 MessageStore 时。

LockRegistry 用于根据键(聚合器使用 correlationId)“查找”锁。默认情况下,ZookeeperLockRegistry 中的锁在 zookeeper 中以下面的路径维护: /SpringIntegration-LockRegistry/ 。你可以通过提供 ZookeeperLockRegistry.KeyToPathStrategy 的实现来自定义路径,如下例所示:

public interface KeyToPathStrategy {

String pathFor(String key);

boolean bounded();

}
java

如果策略从 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" />
xml

client 是对 CuratorFramework bean 的引用。有一个可用的 CuratorFrameworkFactoryBean。当选举出一个领导者时,会为角色 cluster 发布一个 OnGrantedEvent 事件。该角色中的任何端点都会启动。当领导权被撤销时,会为角色 cluster 发布一个 OnRevokedEvent 事件。该角色中的任何端点都会停止。更多信息,请参阅 Endpoint Roles

你可以使用 Java 配置来创建 leader initiator 的实例,如下例所示:

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

从 5.3 版本开始,在 LeaderInitiatorFactoryBean 中暴露了一个 candidate 选项,以提供更多对外部提供的 Candidate 实例的配置控制。只需提供 candidaterole 选项中的一个,但不能同时提供两个;role 选项会在内部创建一个带有 UUIDDefaultCandidate 实例,用于 id 选项。