`

curator leader选举 官方实例

    博客分类:
  • java
 
阅读更多

/**

 * Licensed to the Apache Software Foundation (ASF) under one

 * or more contributor license agreements.  See the NOTICE file

 * distributed with this work for additional information

 * regarding copyright ownership.  The ASF licenses this file

 * to you under the Apache License, Version 2.0 (the

 * "License"); you may not use this file except in compliance

 * with the License.  You may obtain a copy of the License at

 *

 *   http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing,

 * software distributed under the License is distributed on an

 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY

 * KIND, either express or implied.  See the License for the

 * specific language governing permissions and limitations

 * under the License.

 */

package leader;

 

import com.google.common.collect.Lists;

import org.apache.curator.utils.CloseableUtils;

import org.apache.curator.framework.CuratorFramework;

import org.apache.curator.framework.CuratorFrameworkFactory;

import org.apache.curator.retry.ExponentialBackoffRetry;

import org.apache.curator.test.TestingServer;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.List;

 

public class LeaderSelectorExample

{

    private static final int        CLIENT_QTY = 3;

 

    private static final String     PATH = "/examples/leader";

 

    public static void main(String[] args) throws Exception

    {

        // all of the useful sample code is in ExampleClient.java

 

        System.out.println("Create " + CLIENT_QTY + " clients, have each negotiate for leadership and then wait a random number of seconds before letting another leader election occur.");

        System.out.println("Notice that leader election is fair: all clients will become leader and will do so the same number of times.");

 

        List<CuratorFramework>  clients = Lists.newArrayList();

        List<ExampleClient>     examples = Lists.newArrayList();

        TestingServer           server = new TestingServer();

        

          

        try

        {

            for ( int i = 5; i < 7; ++i )

            {

                CuratorFramework    client = CuratorFrameworkFactory.

                newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));

                

                clients.add(client);

 

                ExampleClient       example = new ExampleClient(client, PATH, "Client==== #" + i);

                examples.add(example);

 

                client.start();

                example.start();

            }

            

            

            for ( int i = 1; i < 3; ++i )

            {

                CuratorFramework    client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));

                clients.add(client2);

 

                ExampleClient       example = new ExampleClient(client2, PATH, "Client==== #" + i);

                examples.add(example);

 

                client2.start();

                example.start();

            }

 

            System.out.println("Press enter/return to quit\n");

            new BufferedReader(new InputStreamReader(System.in)).readLine();

        }

        finally

        {

            System.out.println("Shutting down...");

 

            for ( ExampleClient exampleClient : examples )

            {

                CloseableUtils.closeQuietly(exampleClient);

            }

            for ( CuratorFramework client : clients )

            {

                CloseableUtils.closeQuietly(client);

            }

 

            CloseableUtils.closeQuietly(server);

        }

    }

}

 

 

 

 

package leader;

 

import java.io.Closeable;

import java.io.IOException;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicInteger;

 

import org.apache.curator.framework.CuratorFramework;

import org.apache.curator.framework.recipes.leader.LeaderSelector;

import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;

 

/**

 * An example leader selector client. Note that {@link LeaderSelectorListenerAdapter} which

 * has the recommended handling for connection state issues

 */

public class ExampleClient extends LeaderSelectorListenerAdapter implements Closeable

{

    private final String name;

    private final LeaderSelector leaderSelector;

    private final AtomicInteger leaderCount = new AtomicInteger();

 

    public ExampleClient(CuratorFramework client, String path, String name)

    {

        this.name = name;

 

        // create a leader selector using the given path for management

        // all participants in a given leader selection must use the same path

        // ExampleClient here is also a LeaderSelectorListener but this isn't required

        leaderSelector = new LeaderSelector(client, path, this);

 

        // for most cases you will want your instance to requeue when it relinquishes leadership

        leaderSelector.autoRequeue();

    }

 

    public void start() throws IOException

    {

        // the selection for this instance doesn't start until the leader selector is started

        // leader selection is done in the background so this call to leaderSelector.start() returns immediately

        leaderSelector.start();

    }

 

    public void close() throws IOException

    {

        leaderSelector.close();

    }

 

    public void takeLeadership(CuratorFramework client) throws Exception

    {

        // we are now the leader. This method should not return until we want to relinquish leadership

 

        final int         waitSeconds = (int)(5 * Math.random()) + 1;

 

        System.out.println(name + " is now the leader. Waiting " + waitSeconds + " seconds...");

        System.out.println(name + " has been leader " + leaderCount.getAndIncrement() + " time(s) before.");

        try

        {

            Thread.sleep(TimeUnit.SECONDS.toMillis(waitSeconds));

        }

        catch ( InterruptedException e )

        {

            System.err.println(name + " was interrupted.");

            Thread.currentThread().interrupt();

        }

        finally

        {

            System.out.println(name + " relinquishing leadership.\n");

        }

    }

}

分享到:
评论

相关推荐

    apache-curator.rar

    - ** recipes**:预定义的高级功能集合,如 Leader选举、分布式锁、队列、缓存等。 3. **Curator recipes**: - **Leader Election**:确保集群中只有一个节点作为领导者,其他节点成为追随者。 - **Distributed...

    zookeeper客户端curator操作示例

    Curator提供了一系列高级配方,如分布式计数器、队列、 Leader选举、分布式命名服务等,这些配方可以帮助开发者快速构建分布式应用。 6. **重试策略**: 当ZooKeeper操作失败时,Curator可以配置不同的重试策略,...

    zookeeper Java api - curator 5.6.0

    7. **集群状态管理**:Curator 的 `LeaderSelector` 功能允许在集群中选举领导者,确保只有一个节点执行特定任务。例如: ```java LeaderSelector selector = new LeaderSelector(client, "/leader", (client1, ...

    ZooKeeper-Curator:zookeeper的curator客户端

    - Curator提供了一些预定义的模式,如Leader选举、分布式计数器、队列和锁等,简化了常见的分布式编程问题。 6. **Curator Recipes** - `Leader Election`:实现分布式环境中的领导者选举。 - `Locks`:提供...

    VIP-02 Zookeeper客户端使用与集群特性(1)

    - **封装常用功能**:Curator提供了一系列的API,用于实现诸如Leader选举、分布式锁、分布式计数器等功能,这大大减轻了开发者的工作量。 - **会话管理**:Curator内部实现了会话的自动重连机制,当ZooKeeper会话...

    zookeeper中文文档

    在Zookeeper中,可以通过Leader选举算法来选择集群中的Leader节点,而FlashLeaderElection算法是其中的一种实现。 Zookeeper的Watch机制能够使客户端在指定的节点发生变化时得到通知。ACL控制则提供了一种安全机制...

    java-zookeeper:动物园管理员

    - **Leader选举**:利用`LeaderSelector`实现服务实例间的选举。 6. **实际应用** - **Hadoop**:Zookeeper在Hadoop中用于协调NameNode和DataNode,确保集群的稳定性。 - **Kafka**:管理生产者和消费者的元数据...

    1000道 互联网Java工程师面试题 485页

    - **选举新Leader**:如果Leader节点宕机,集群会重新选举新的Leader。 #### 18、zookeeper负载均衡和nginx负载均衡区别 - **zookeeper**:基于数据节点的状态来实现负载均衡,侧重于服务发现和集群管理。 - **...

    1000道 互联网Java工程师面试题 485页_PDF密码解除.pdf

    - **Curator:**Apache Curator库,提供高级功能和异常处理。 **24. chubby是什么,和zookeeper比你怎么看?** - **Chubby:**Google开发的一个分布式锁服务。 - **比较:**Chubby和ZooKeeper都提供类似的分布式...

    ZooKeeper面试题(2022最新版)-重点.docx

    ZooKeeper提供了官方的Java客户端库,此外还有一些社区开发的客户端库,例如Curator和ZKClient等。 #### 25. Chubby是什么,和Zookeeper比较有何看法? Chubby是由Google开发的一个分布式锁服务,与ZooKeeper有...

Global site tag (gtag.js) - Google Analytics