本文整理汇总了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();
}
示例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);
}
示例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());
}
示例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);
}
}
示例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");
}
示例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();
}
示例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);
}
示例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);
}
示例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);
}
示例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();
}
示例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);
}
}
示例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);
}