本文整理匯總了Java中org.apache.curator.framework.imps.CuratorFrameworkState類的典型用法代碼示例。如果您正苦於以下問題:Java CuratorFrameworkState類的具體用法?Java CuratorFrameworkState怎麽用?Java CuratorFrameworkState使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
CuratorFrameworkState類屬於org.apache.curator.framework.imps包,在下文中一共展示了CuratorFrameworkState類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: TopicPartition
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
/**
* 在拉完全量後將此schema的kafka consumer的offset設置為最新
* @param dbSchema
*/
/*public void setKafkaOffsetToLargest(String targetTopic){
if(targetTopic==null)
return;
TopicPartition partition0 = new TopicPartition(targetTopic, 0);
KafkaConsumerContainer.getInstances().getConsumer(targetTopic).seekToEnd(Arrays.asList(partition0));
}*/
protected <T> T deserialize(String path, Class<T> clazz) throws Exception {
T packet = null;
CuratorFramework curator = CuratorContainer.getInstance().getCurator();
if (curator.getState() == CuratorFrameworkState.STOPPED) {
LOG.info("[EventContainer] CuratorFrameworkState:{}", CuratorFrameworkState.STOPPED.name());
} else {
byte[] bytes = curator.getData().forPath(path);
if (bytes != null && bytes.length != 0) {
packet = JsonUtil.fromJson(new String(bytes, Charset.forName("UTF-8")), clazz);
}
}
return packet;
}
示例2: init
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
/**
* 初始化
*
* @author zhangshaobin
* @created 2013-6-26 上午10:55:30
*/
private void init() {
applicationName = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.CONFIG_APPLICATION_NAME_KEY, null).get();
String zkConfigEnsemble = DynamicPropertyFactory.getInstance().getStringProperty(CommonConstant.ZK_ENSEMABLE_KEY, null).get();
Integer zkConfigSessionTimeout = DynamicPropertyFactory.getInstance().getIntProperty(CommonConstant.ZK_SESSION_TIMEOUT_KEY, 15000).get();
Integer zkConfigConnTimeout = DynamicPropertyFactory.getInstance().getIntProperty(CommonConstant.ZK_CONN_TIMEOUT_KEY, 5000).get();
if (Check.NuNStr(zkConfigEnsemble)) {
logger.warn("ZooKeeper configuration running in file mode, zk is not enabled since not configured");
return;
}
try {
client = createAndStartZKClient(zkConfigEnsemble, zkConfigSessionTimeout, zkConfigConnTimeout);
if (client.getState() != CuratorFrameworkState.STARTED) {
throw new RuntimeException("ZooKeeper located at " + zkConfigEnsemble + " is not started.");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("連接配置中心服務器超時,時間5000毫秒。", e.getCause());
System.exit(1);
}
System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date()) + applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
logger.info(applicationName + " connected to cofnig server(" + zkConfigEnsemble + ").");
}
示例3: register
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
@Override
public void register(String service, String version, String address) {
if(zkClient.getState() == CuratorFrameworkState.LATENT){
zkClient.start();
}
if (version == null || version == ""){
version ="1.0.0";
}
//創建臨時節點
try {
zkClient.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL)
.forPath("/"+service+"/"+version+"/"+address);
} catch (Exception e) {
logger.error("register service address to zookeeper exception:{}",e);
throw new ThriftException("register service address to zookeeper exception:{}", e);
}
}
示例4: register
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
@Override
public void register(String service, String version, String address) {
if(curatorFramework.getState() == CuratorFrameworkState.LATENT){
curatorFramework.start();
}
if (version == null || version == ""){
version = ThriftConstant.DEFAULT_VERSION;
}
//創建臨時節點
try {
String path = "/"+service+"/"+version+"/"+address;
logger.info("register: {}", path);
curatorFramework.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
.forPath(path);
} catch (Exception e) {
logger.error("register service address to zookeeper exception:{}",e);
throw new ThriftException("register service address to zookeeper exception:{}", e);
}
}
示例5: relinquishLeadership
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
@Override
public void relinquishLeadership() {
try {
if (nodeCache != null) {
nodeCache.close();
}
LoggerHelper.info("node cache has been closed.");
} catch (Throwable e) {
LoggerHelper.warn("node cache close failed.", e);
}
if (client.getState() == CuratorFrameworkState.STARTED) {
MasterSlaveNodeData.Data nodeData = new MasterSlaveNodeData.Data(getNodeIp());
releaseJobs(nodePath, nodeData);
nodeData.setNodeState("Slave");
masterSlaveApiFactory.nodeApi().updateNode(nodePath, nodeData);
}
LoggerHelper.info("clear node successfully.");
}
示例6: relinquishLeadership
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
@Override
public void relinquishLeadership() {
try {
if (jobCache != null) {
jobCache.close();
}
LoggerHelper.info("job cache has been closed.");
} catch (Throwable e) {
LoggerHelper.warn("job cache close failed.", e);
}
LoggerHelper.info("begin stop scheduler manager.");
schedulerManager.shutdown();
if (client.getState() == CuratorFrameworkState.STARTED) {
StandbyNodeData.Data data = new StandbyNodeData.Data(getNodeIp());
standbyApiFactory.nodeApi().updateNode(nodePath, data);
LoggerHelper.info(getNodeIp() + " has been shutdown. [" + data + "]");
}
LoggerHelper.info("clear node successfully.");
}
示例7: save
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
public void save(SingularityHostState hostState) throws InterruptedException {
final String path = ZKPaths.makePath(ROOT_PATH, hostState.getHostname());
final byte[] data = hostStateTranscoder.toBytes(hostState);
if (curator.getState() == CuratorFrameworkState.STARTED) {
try {
if (exists(path)) {
curator.setData().forPath(path, data);
} else {
curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, data);
}
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
}
示例8: testConnect
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
/**
* Test the timeout exception
*
* @throws IOException
* @throws InterruptedException
*/
@Test
public void testConnect() throws IOException, InterruptedException {
// we expect a ConnectException to be thrown
final ZConnection conn = new ZConnection("localhost:" + server.getPort(), 10000L);
try {
CuratorFramework zk = conn.get();
assertTrue(zk.getState().compareTo(CuratorFrameworkState.STARTED) == 0);
} finally {
conn.close();
}
}
示例9: buildServiceDiscoveryWith
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
private ServiceDiscovery<ZookeeperInstance> buildServiceDiscoveryWith(ZookeeperConfiguration configuration, CuratorFramework curator,
InstanceSerializer<ZookeeperInstance> serializer) {
try {
if (!CuratorFrameworkState.STARTED.equals(curator.getState())) {
curator.start();
}
ServiceDiscovery<ZookeeperInstance> serviceDiscovery = ServiceDiscoveryBuilder.builder(ZookeeperInstance.class)
.client(curator)
.basePath(configuration.root())
.serializer(serializer)
.build();
serviceDiscovery.start();
return serviceDiscovery;
} catch (Exception e) {
throw new ZookeeperServiceDiscoveryException("Error on create Zookeeper ServiceDiscovery", e);
}
}
示例10: wait
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
@Override
public WaitResult wait(DockerFacade dockerClient, Container container) {
return new PortWait().wait(ZOOKEEPER_PORT, dockerClient, container, (ipAddress, externalPort) -> {
String zookeeperConnectionString = String.format("%s:%s", ipAddress, externalPort);
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
client.start();
try {
client.blockUntilConnected();
CuratorFrameworkState status = client.getState();
if (!status.equals(CuratorFrameworkState.STARTED)) {
return WaitResult.failure("Status [%s] does not match expected [STARTED]", status);
}
return WaitResult.success();
} catch (InterruptedException e) {
throw new RuntimeException("Could not connect to Zookeeper", e);
} finally {
client.close();
}
});
}
示例11: readCurrentMapping
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
private synchronized ZMapping readCurrentMapping(Stat stat) {
ZMapping zMap = null;
try {
if (client.getState().equals(CuratorFrameworkState.STOPPED)) {
LOG.warn("Attempting to read state on stopped client.");
return null;
}
byte[] data = client.getData().storingStatIn(stat).usingWatcher(new CuratorWatcher() {
@Override
public void process(WatchedEvent watchedEvent) throws Exception {
ZMapping newMapping = readCurrentMapping();
if (newMapping == null && mapping != null) {
LOG.warn("An attempt was made to overwrite current mapping with a null one.");
} else {
mapping = newMapping;
}
LOG.debug("Host {} just updated its mapping to version {}", hostPort, (mapping != null) ? mapping.getVersion() : -1);
}
}).forPath(MAPPING_PATH);
zMap = ZMapping.deserialize(data);
} catch (Exception e) {
LOG.error("Error reading current mapping: ", e);
}
return zMap;
}
示例12: doHealthCheck
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
try {
if (this.curator.getState() != CuratorFrameworkState.STARTED) {
builder.down().withDetail("error", "Client not started");
}
else if (this.curator.checkExists().forPath("/") == null) {
builder.down().withDetail("error", "Root for namespace does not exist");
}
else {
builder.up();
}
builder.withDetail("connectionString",
this.curator.getZookeeperClient().getCurrentConnectionString())
.withDetail("state", this.curator.getState());
}
catch (Exception e) {
builder.down(e);
}
}
示例13: ZKUtils
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
private ZKUtils(String zookeeperCluster, String groupId) throws Exception {
this.groupId = groupId;
// ZOOKEPER CONNECTION
client = CuratorFrameworkFactory.newClient(zookeeperCluster, 25 * 1000, 10 * 1000, new ExponentialBackoffRetry(
1000, 3));
client.start();
client.getZookeeperClient().blockUntilConnectedOrTimedOut();
if (client.getState().compareTo(CuratorFrameworkState.STARTED) != 0) {
throw new Exception("Connection to Zookeeper timed out after seconds");
} else {
backgroundZookeeperCleanerTasks = Executors.newFixedThreadPool(1);
backgroundZookeeperCleanerTasks.submit(new ZookeeperBackgroundCleaner(client, groupId));
}
}
示例14: testStart
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
@SuppressWarnings("unchecked")
@Test
public void testStart() throws Exception {
CuratorFramework framework = mockFramework();
ExistsBuilder ceBuilder = mock(ExistsBuilder.class);
CreateBuilder createBuilder = mock(CreateBuilder.class);
when(framework.checkExists()).thenReturn(ceBuilder);
when(ceBuilder.forPath("/services/myservice/nodes")).thenReturn(mock(Stat.class));
when(framework.create()).thenReturn(createBuilder);
when(framework.getState()).thenReturn(CuratorFrameworkState.STARTED);
ACLBackgroundPathAndBytesable<String> os = mock(ACLBackgroundPathAndBytesable.class);
when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(os);
DiscoService service = new DiscoService(framework, "myservice");
byte[] payload = "foo bar baz bingo".getBytes();
service.start("foo", 4321, true, payload);
verify(os).forPath(eq("/services/myservice/nodes/foo:4321"), eq(payload));
}
示例15: testDeletesEphemeralNode
import org.apache.curator.framework.imps.CuratorFrameworkState; //導入依賴的package包/類
@SuppressWarnings("unchecked")
@Test
public void testDeletesEphemeralNode() throws Exception {
CuratorFramework framework = mockFramework();
ExistsBuilder ceBuilder = mock(ExistsBuilder.class);
CreateBuilder createBuilder = mock(CreateBuilder.class);
when(framework.checkExists()).thenReturn(ceBuilder);
when(ceBuilder.forPath("/services/myservice/nodes")).thenReturn(mock(Stat.class));
when(ceBuilder.forPath("/services/myservice/nodes/foo:4321")).thenReturn(mock(Stat.class));
when(framework.create()).thenReturn(createBuilder);
when(framework.getState()).thenReturn(CuratorFrameworkState.STARTED);
DeleteBuilder deleteBuilder = mock(DeleteBuilder.class);
when(framework.delete()).thenReturn(deleteBuilder);
ACLBackgroundPathAndBytesable<String> os = mock(ACLBackgroundPathAndBytesable.class);
when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(os);
DiscoService service = new DiscoService(framework, "myservice");
byte[] payload = "foo bar baz bingo".getBytes();
service.start("foo", 4321, true, payload);
verify(deleteBuilder).forPath("/services/myservice/nodes/foo:4321");
verify(os).forPath(eq("/services/myservice/nodes/foo:4321"), eq(payload));
}