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
实例进行更精细的配置控制。candidate
或 role
选项只需提供一个,不能同时提供两个;role
选项会在内部创建一个 DefaultCandidate
实例,其 id
选项使用 UUID
。