当前位置: 首页>>代码示例>>Java>>正文


Java LeaderLatch.addListener方法代码示例

本文整理汇总了Java中org.apache.curator.framework.recipes.leader.LeaderLatch.addListener方法的典型用法代码示例。如果您正苦于以下问题:Java LeaderLatch.addListener方法的具体用法?Java LeaderLatch.addListener怎么用?Java LeaderLatch.addListener使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.curator.framework.recipes.leader.LeaderLatch的用法示例。


在下文中一共展示了LeaderLatch.addListener方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: run

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
@Override
public void run(String... strings) throws Exception {
    client = CuratorFrameworkFactory.newClient(zookeeperConnString,
            new ExponentialBackoffRetry(1000, Integer.MAX_VALUE));
    client.start();
    client.getZookeeperClient().blockUntilConnectedOrTimedOut();

    leaderLatch = new LeaderLatch(client, "/http-job-scheduler/leader",
            ManagementFactory.getRuntimeMXBean().getName());

    leaderLatch.addListener(new LeaderLatchListener() {
        @Override
        public void isLeader() {
            setMaster(true);
            masterJobScheduler.resume();
        }

        @Override
        public void notLeader() {
            setMaster(false);
            masterJobScheduler.pause();
        }
    });
    leaderLatch.start();
}
 
开发者ID:flipkart-incubator,项目名称:simpleJobScheduler,代码行数:26,代码来源:Application.java

示例2: elect

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
@Override
public void elect() throws Exception {
	
	zkClient.createContainers(ctx.getLeaderElectionZKPath());
	
	latch = new LeaderLatch(zkClient, ctx.getLeaderElectionZKPath(), ctx.getLeaderElectionID());
	latch.addListener(new LeaderLatchListener() {

		@Override
		public void notLeader() {
		}

		@Override
		public void isLeader() {
		}
	});

	latch.start();
	logger.info("[elect]{}", ctx);
}
 
开发者ID:ctripcorp,项目名称:x-pipe,代码行数:21,代码来源:DefaultLeaderElector.java

示例3: addListenerToLeaderLatch

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
private void addListenerToLeaderLatch(LeaderLatch leaderLatch)
{

    LeaderLatchListener listener = new LeaderLatchListener()
    {
        @Override
        public void isLeader()
        {
            reapingIsActive.set(true);
            for ( PathHolder holder : activePaths.values() )
            {
                schedule(holder, reapingThresholdMs);
            }
        }

        @Override
        public void notLeader()
        {
            reapingIsActive.set(false);
        }
    };
    leaderLatch.addListener(listener);

    reapingIsActive.set(leaderLatch.hasLeadership());
}
 
开发者ID:apache,项目名称:curator,代码行数:26,代码来源:Reaper.java

示例4: process

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
@SuppressWarnings("resource")
@Override
public void process() {
    try {
        CuratorFramework _curator = CuratorContainer.getInstance().getCurator();
        HeartBeatVo conf = HeartBeatConfigContainer.getInstance().getHbConf();
        CuratorContainer.getInstance().createZkNode(conf.getLeaderPath());

        // 获取进程ID和服务器hostName
        final BrokerInfoVo brokerInfo = new BrokerInfoVo();
        String name = ManagementFactory.getRuntimeMXBean().getName();
        String[] pidAndHostName = StringUtils.split(name, "@");
        brokerInfo.setPid(pidAndHostName[0]);
        brokerInfo.setHostName(pidAndHostName[1]);
        brokerInfo.setIp(InetAddress.getLocalHost().getHostAddress());
        LeaderLatch ll = new LeaderLatch(_curator, conf.getLeaderPath(), JsonUtil.toJson(brokerInfo));

        ll.addListener(new LeaderLatchListener() {
            @Override
            public void notLeader() {
                LoggerFactory.getLogger().error("本机现在切换到非leader状态,准备终止当前进程PID:{}", brokerInfo.getPid());
                System.exit(-1);
            }
            @Override
            public void isLeader() {
                LoggerFactory.getLogger().info("本机现在切换到leader状态.");
            }
        });

        ll.start();
        ll.await();
        // 注册控制事件
        CuratorContainer.getInstance().createZkNode(conf.getControlPath());
        _curator.getData().usingWatcher(WatcherType.CONTROL).forPath(conf.getControlPath());
    } catch (Exception e) {
        throw new RuntimeException("选举leader时发生错误!", e);
    }
}
 
开发者ID:BriData,项目名称:DBus,代码行数:39,代码来源:LeaderElectHandler.java

示例5: init

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
/**
 * 阻塞式的初始化和Zookeeper的连接,这个方法在一个容器生命周期中只允许允许一次。
 * <p/>
 * 和zookeeper之间的连接遵循每实例一个ZkClientProvider的方式,这样当实例内部有多个同步线程的时候,
 * 可以共享一个ZkClientProvider,状态都是一致的,避免有些线程是leader,有些是standby的情况。
 * <p/>
 * 改方法是全异步的,如果zookeeper连接不上,也会返回。但是一般上层应用拿不到leader latch,不会成为leader。
 * 而且<code>apache.zookeeper.ClientCnxn</code>包的日志会打印如下:
 * <pre>
 *     Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket
 *     connection and attempting reconnect
 * </pre>
 * 参数<code>name</code>标示同步线程的名称,默认的话只有一个可以初始化好和zk的连接,其他的都不再重复初始化了。
 */
@Override
public void init(String name) {
    if (!state.compareAndSet(State.LATENT, State.STARTED)) {
        logger.debug("ZkHaGuard can only be initialized once because LeaderLatch should be singleton");
        return;
    }

    if (zkClientProvider == null) {
        throw new IllegalStateException("ZkClientProvider should not be null");
    }
    logger.info("LeaderLatch will start soon by " + name);
    zkClientProvider.init();
    leaderLatch = new LeaderLatch(zkClientProvider.provideClient(), latchPath, NetUtils.getLocalHostIP());
    leaderLatch.addListener(new LeaderLatchListener() {
        @Override
        public void isLeader() {
            logger.info("This instance is leader");
        }

        @Override
        public void notLeader() {
            logger.warn("This instance is NOT leader");
        }
    });
    try {
        leaderLatch.start();
    } catch (Exception e) {
        throw new RuntimeException("Leader latch init failed", e);
    }
    logger.info("LeaderLatch starts by " + name + " asynchronously");
}
 
开发者ID:neoremind,项目名称:fountain,代码行数:46,代码来源:ZkHaGuard.java

示例6: start

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
public void start() throws Exception {
    client.start();
    client.getZookeeperClient().blockUntilConnectedOrTimedOut();
    leaderLatch = new LeaderLatch(client, latchpath, id);

    ClusterSyncManagerLeaderListener listener = new ClusterSyncManagerLeaderListener(failOverTask, getNode());
    leaderLatch.addListener(listener);

    leaderLatch.start();
}
 
开发者ID:Stratio,项目名称:Decision,代码行数:11,代码来源:ClusterSyncManager.java

示例7: testRequestControl

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
/**
 * Test if {@link ZookeeperRegistry#requestControl(long, IControllerRegistryService.ControlChangeCallback)}
 * correctly take control of specific switch.
 * Because {@link ZookeeperRegistry#requestControl(long, IControllerRegistryService.ControlChangeCallback)}
 * doesn't return values, inject mock {@link LeaderLatch} object and verify latch is correctly set up.
 *
 * @throws Exception
 */
@Test
public void testRequestControl() throws Exception {
    // Mock LeaderLatch
    LeaderLatch latch = createMock(LeaderLatch.class);
    latch.addListener(anyObject(SwitchLeaderListener.class));
    expectLastCall().once();
    latch.start();
    expectLastCall().once();
    replay(latch);

    PowerMock.expectNew(LeaderLatch.class,
            anyObject(CuratorFramework.class),
            anyObject(String.class),
            anyObject(String.class))
            .andReturn(latch).once();
    PowerMock.replay(LeaderLatch.class);

    String controllerId = "controller2013";
    registry.registerController(controllerId);

    LoggingCallback callback = new LoggingCallback(1);
    long dpidToRequest = 2000L;

    try {
        registry.requestControl(dpidToRequest, callback);
    } catch (RegistryException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    verify(latch);
}
 
开发者ID:opennetworkinglab,项目名称:spring-open,代码行数:41,代码来源:ZookeeperRegistryTest.java

示例8: testReleaseControl

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
/**
 * Test if {@link ZookeeperRegistry#releaseControl(long)} correctly release control of specific switch.
 * Because {@link ZookeeperRegistry#releaseControl(long)} doesn't return values, inject mock
 * {@link LeaderLatch} object and verify latch is correctly set up.
 *
 * @throws Exception
 */
@Test
public void testReleaseControl() throws Exception {
    // Mock of LeaderLatch
    LeaderLatch latch = createMock(LeaderLatch.class);
    latch.addListener(anyObject(SwitchLeaderListener.class));
    expectLastCall().once();
    latch.start();
    expectLastCall().once();
    latch.removeListener(anyObject(SwitchLeaderListener.class));
    expectLastCall().once();
    latch.close();
    expectLastCall().once();
    replay(latch);

    PowerMock.expectNew(LeaderLatch.class,
            anyObject(CuratorFramework.class),
            anyObject(String.class),
            anyObject(String.class))
            .andReturn(latch).once();
    PowerMock.replay(LeaderLatch.class);

    String controllerId = "controller2013";
    registry.registerController(controllerId);

    long dpidToRequest = 2000L;
    LoggingCallback callback = new LoggingCallback(1);

    registry.requestControl(dpidToRequest, callback);
    registry.releaseControl(dpidToRequest);

    verify(latch);
}
 
开发者ID:opennetworkinglab,项目名称:spring-open,代码行数:40,代码来源:ZookeeperRegistryTest.java

示例9: onStart

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
@Override
public void onStart(CuratorFramework curator) throws Exception
{
    leaderLatch = new LeaderLatch(curator, path);
    
    leaderLatch.start();
    leaderLatch.addListener(listener);
}
 
开发者ID:interruptus,项目名称:interruptus,代码行数:9,代码来源:AttachLeaderSelectorListener.java

示例10: initAndStartLeaderLatch

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
private void initAndStartLeaderLatch() throws Exception {
  leaderLatch = new LeaderLatch(curator, latchPath, rmId);
  leaderLatch.addListener(this);
  leaderLatch.start();
}
 
开发者ID:hopshadoop,项目名称:hops,代码行数:6,代码来源:CuratorBasedElectorService.java

示例11: requestControl

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
@Override
public void requestControl(long dpid, ControlChangeCallback cb)
        throws RegistryException {
    log.info("Requesting control for {}", HexString.toHexString(dpid));

    if (onosInstanceId == null) {
        throw new IllegalStateException("Must register a controller before"
                + " calling requestControl");
    }

    String dpidStr = HexString.toHexString(dpid);

    if (switches.get(dpidStr) != null) {
        log.debug("Already contesting {}, returning", HexString.toHexString(dpid));
        throw new RegistryException("Already contesting control for " + dpidStr);
    }

    String latchPath = SWITCH_LATCHES_PATH + "/" + dpidStr;

    LeaderLatch latch =
        new LeaderLatch(curatorFrameworkClient, latchPath,
                        onosInstanceId.toString());
    SwitchLeaderListener listener = new SwitchLeaderListener(dpidStr);
    latch.addListener(listener);


    SwitchLeadershipData swData = new SwitchLeadershipData(latch, cb, listener);
    SwitchLeadershipData oldData = switches.putIfAbsent(dpidStr, swData);

    if (oldData != null) {
        // There was already data for that key in the map
        // i.e. someone else got here first so we can't succeed
        log.debug("Already requested control for {}", dpidStr);
        throw new RegistryException("Already requested control for " + dpidStr);
    }

    // Now that we know we were able to add our latch to the collection,
    // we can start the leader election in Zookeeper. However I don't know
    // how to handle if the start fails - the latch is already in our
    // switches list.
    // TODO seems like there's a Curator bug when latch.start is called when
    // there's no Zookeeper connection which causes two znodes to be put in
    // Zookeeper at the latch path when we reconnect to Zookeeper.
    try {
        latch.start();
    } catch (Exception e) {
        log.warn("Error starting leader latch: {}", e.getMessage());
        throw new RegistryException("Error starting leader latch for "
                + dpidStr, e);
    }

}
 
开发者ID:opennetworkinglab,项目名称:spring-open,代码行数:53,代码来源:ZookeeperRegistry.java

示例12: testHasControl

import org.apache.curator.framework.recipes.leader.LeaderLatch; //导入方法依赖的package包/类
/**
 * Test if {@link ZookeeperRegistry#hasControl(long)} returns
 * correct status whether controller has control of specific switch.
 *
 * @throws Exception
 */
@Test
public void testHasControl() throws Exception {
    // Mock of LeaderLatch
    LeaderLatch latch = createMock(LeaderLatch.class);
    latch.addListener(anyObject(SwitchLeaderListener.class));
    expectLastCall().once();
    latch.start();
    expectLastCall().once();
    expect(latch.hasLeadership()).andReturn(true).anyTimes();
    latch.removeListener(anyObject(SwitchLeaderListener.class));
    expectLastCall().once();
    latch.close();
    expectLastCall().once();
    replay(latch);

    PowerMock.expectNew(LeaderLatch.class,
            anyObject(CuratorFramework.class),
            anyObject(String.class),
            anyObject(String.class))
            .andReturn(latch);
    PowerMock.replay(LeaderLatch.class);

    String controllerId = "controller2013";
    registry.registerController(controllerId);

    long dpidToRequest = 2000L;
    LoggingCallback callback = new LoggingCallback(2);

    // Test before request control
    assertFalse(registry.hasControl(dpidToRequest));

    registry.requestControl(dpidToRequest, callback);

    // Test after request control
    assertTrue(registry.hasControl(dpidToRequest));

    registry.releaseControl(dpidToRequest);

    // Test after release control
    assertFalse(registry.hasControl(dpidToRequest));

    verify(latch);
}
 
开发者ID:opennetworkinglab,项目名称:spring-open,代码行数:50,代码来源:ZookeeperRegistryTest.java


注:本文中的org.apache.curator.framework.recipes.leader.LeaderLatch.addListener方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。