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 实例。candidaterole 选项只需提供其中一个,但不能同时提供;role 选项会在内部创建一个 DefaultCandidate 实例,其中 id 选项为 UUID

© . This site is unofficial and not affiliated with VMware.