奉贤建设机械网站,wordpress 群晖 局域网,wordpress代码缩进,网站代码优化jgroups嗨#xff0c;您好#xff0c; 在本文中#xff0c;我将展示如何在不使用任何其他基础架构#xff08;例如Apache Zookeeper或Consul#xff09;的情况下解决领导人选举的问题。 领导者选举是解决以下问题的一种常见方法#xff1a;在分布式系统中#xff0c;只… jgroups 嗨您好 在本文中我将展示如何在不使用任何其他基础架构例如Apache Zookeeper或Consul的情况下解决领导人选举的问题。 领导者选举是解决以下问题的一种常见方法在分布式系统中只有一个实例必须完成特定工作。 例如这可能是 触发计划的工作 当系统充当外部系统的客户端时协调建立连接 运行清理任务 … 通常这可以通过使用提到的或类似的基础结构来解决。 但是如果您不想将它们引入系统环境则还有另一种方法 JGroups 。 JGroups是一个 用于可靠消息传递的工具包。 它可用于创建其节点可以相互发送消息的集群。 [http://jgroups.org/] 使用JGroups设置领导者可以通过使用JGroups的View概念非常容易地进行选举。 视图是关于群集状态的实际视图请猜测是什么。 由于每个集群都恰好有一个协调器它是视图中成员列表的第一个成员因此可以将其解释为集群的领导者。 如果领导者死亡/重新启动/出现故障列表中的下一个成员将成为新的领导者。 这是一种非常方便且确定的方法。 例 让我们看一些简单的代码演示一下 public class JGroupsLeaderElectionExample {private static final int MAX_ROUNDS 1_000;private static final int SLEEP_TIME_IN_MILLIS 1000;public static void main(String[] args) throws Exception {JChannel channel new JChannel();channel.connect(The Test Cluster);for (int round 0; round MAX_ROUNDS; round) {checkLeaderStatus(channel);sleep();}channel.close();}private static void sleep() {try {Thread.sleep(SLEEP_TIME_IN_MILLIS);} catch (InterruptedException e) {// Ignored}}private static void checkLeaderStatus(JChannel channel) {View view channel.getView();Address address view.getMembers().get(0);if (address.equals(channel.getAddress())) {System.out.println(Im ( channel.getAddress() ) the leader);} else {System.out.println(Im ( channel.getAddress() ) not the leader);}}
} 上面的代码使用默认的堆栈设置创建一个新的JChannel。 也可以使用XML文件或编程方法来配置堆栈。 然后将通道连接到“测试群集” 。 JGroups通过在连接上广播发现集群。 如果当前实例是第一个它将创建集群。 在循环中代码现在仅从通道获取实际视图并检查实际实例是否也是第一个成员。 您记得第一位成员可以被视为领导者。 如果现在启动多个实例并停止第一个实例则第二个将接管。 像这个例子 -------------------------------------------------------------------
GMS: addressYgdrassil-21922, clusterThe Test Cluster, physical address2003:4e:a904:2d67:55c:2653:7e28:8634:59721
-------------------------------------------------------------------
Im (Ygdrassil-21922) the leader
Im (Ygdrassil-21922) the leader
Im (Ygdrassil-21922) the leader
Im (Ygdrassil-21922) the leader-------------------------------------------------------------------
GMS: addressYgdrassil-57947, clusterThe Test Cluster, physical address2003:4e:a904:2d67:55c:2653:7e28:8634:59724
-------------------------------------------------------------------
Im (Ygdrassil-57947) not the leader
Im (Ygdrassil-57947) not the leader
Im (Ygdrassil-57947) not the leader
Im (Ygdrassil-57947) not the leader
Im (Ygdrassil-57947) not the leader
Im (Ygdrassil-57947) the leader
Im (Ygdrassil-57947) the leader 像往常一样可以在我的GitHub帐户上找到该代码。 摘要 在本文中我们了解了如何在不引入任何其他基础结构的情况下设置领导者选举。 JGroups提供了很多有趣的东西例如分布式计数器分布式任务执行等。 翻译自: https://www.javacodegeeks.com/2016/06/jgroups-leader-election-without-additional-infrastructure.htmljgroups