本文整理匯總了Java中org.apache.curator.framework.CuratorFramework類的典型用法代碼示例。如果您正苦於以下問題:Java CuratorFramework類的具體用法?Java CuratorFramework怎麽用?Java CuratorFramework使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
CuratorFramework類屬於org.apache.curator.framework包,在下文中一共展示了CuratorFramework類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: notifyClusterDDL
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
public void notifyClusterDDL(String schema, String table, String sql, DDLInfo.DDLStatus ddlStatus, boolean needNotifyOther) throws Exception {
CuratorFramework zkConn = ZKUtils.getConnection();
DDLInfo ddlInfo = new DDLInfo(schema, sql, ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID), ddlStatus);
String nodeName = StringUtil.getFullName(schema, table);
String nodePath = ZKPaths.makePath(KVPathUtil.getDDLPath(), nodeName);
if (zkConn.checkExists().forPath(nodePath) == null) {
zkConn.create().forPath(nodePath, ddlInfo.toString().getBytes(StandardCharsets.UTF_8));
} else {
String instancePath = ZKPaths.makePath(nodePath, KVPathUtil.DDL_INSTANCE);
String thisNode = ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID);
ZKUtils.createTempNode(instancePath, thisNode);
if (needNotifyOther) {
//this node is ddl sender
zkConn.setData().forPath(nodePath, ddlInfo.toString().getBytes(StandardCharsets.UTF_8));
while (true) {
List<String> preparedList = zkConn.getChildren().forPath(instancePath);
List<String> onlineList = zkConn.getChildren().forPath(KVPathUtil.getOnlinePath());
if (preparedList.size() >= onlineList.size()) {
zkConn.delete().deletingChildrenIfNeeded().forPath(nodePath);
break;
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
}
}
}
}
示例2: get
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
@Override
public CuratorFramework get() {
String quorum = zookeeperConfig.getQuorum();
String serviceDiscoveryPath = zookeeperConfig.getServiceDiscoveryPath();
String connectionString = quorum + (serviceDiscoveryPath == null ? "" : serviceDiscoveryPath);
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
LOGGER.info("Initiating Curator connection to Zookeeper using: [{}]", connectionString);
// Use chroot so all subsequent paths are below /stroom-services to avoid conflicts with hbase/zookeeper/kafka etc.
CuratorFramework client = CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
client.start();
try {
//Ensure the chrooted path for stroom-services exists
Stat stat = client.checkExists().forPath("/");
if (stat == null) {
LOGGER.info("Creating chroot-ed root node inside " + serviceDiscoveryPath);
client.create().forPath("/");
}
} catch (Exception e) {
throw new RuntimeException("Error connecting to zookeeper using connection String: " + connectionString, e);
}
return client;
}
示例3: createConnection
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
private static CuratorFramework createConnection() {
String url = ZkConfig.getInstance().getZkURL();
CuratorFramework framework = CuratorFrameworkFactory.newClient(url, new ExponentialBackoffRetry(100, 6));
// start connection
framework.start();
// wait 3 second to establish connect
try {
framework.blockUntilConnected(3, TimeUnit.SECONDS);
if (framework.getZookeeperClient().isConnected()) {
LOGGER.info("CuratorFramework createConnection success");
return framework;
}
} catch (InterruptedException ignored) {
LOGGER.info("CuratorFramework createConnection error", ignored);
Thread.currentThread().interrupt();
}
// fail situation
framework.close();
throw new RuntimeException("failed to connect to zookeeper service : " + url);
}
示例4: createConnection
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
private static CuratorFramework createConnection() {
String url= ZkConfig.getInstance().getZkURL();
CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(url, new ExponentialBackoffRetry(100, 6));
// start connection
curatorFramework.start();
// wait 3 second to establish connect
try {
curatorFramework.blockUntilConnected(3, TimeUnit.SECONDS);
if (curatorFramework.getZookeeperClient().isConnected()) {
return curatorFramework;
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// fail situation
curatorFramework.close();
throw new RuntimeException("failed to connect to zookeeper service : " + url);
}
示例5: ZooMap
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
private ZooMap(Builder builder) {
this.connectionString = builder.connectionString;
ConnectStringParser connectStringParser = new ConnectStringParser(connectionString);
if(connectStringParser.getChrootPath() != null) {
final String connectionStringForChrootCreation = connectStringParser.getServerAddresses().stream().map(InetSocketAddress::toString).collect(Collectors.joining(","));
try(final CuratorFramework clientForChrootCreation = newCuratorFrameworkClient(builder, connectionStringForChrootCreation)) {
startAndBlock(clientForChrootCreation);
tryIt(() -> clientForChrootCreation.createContainers(connectStringParser.getChrootPath()));
}
}
client = newCuratorFrameworkClient(builder, connectionString);
this.root = builder.root;
startAndBlock(client);
if(!root.isEmpty()) {
tryIt(() -> client.createContainers(root));
}
}
示例6: setUp
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
Configurator
.initialize("FastMQ", Thread.currentThread().getContextClassLoader(), "log4j2.xml");
Log log = new Log();
LogSegment logSegment = new LogSegment();
logSegment.setLedgerId(ledgerId);
logSegment.setTimestamp(System.currentTimeMillis());
log.setSegments(Collections.singletonList(logSegment));
when(logInfoStorage.getLogInfo(any())).thenReturn(log);
CuratorFramework curatorFramework = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));
curatorFramework.start();
asyncCuratorFramework = AsyncCuratorFramework.wrap(curatorFramework);
offsetStorage = new ZkOffsetStorageImpl(logInfoStorage, asyncCuratorFramework);
}
示例7: ZkAbstractStore
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
public ZkAbstractStore(CuratorFramework framework, PStoreConfig<V> config)
throws IOException {
this.parent = "/" + config.getName();
this.prefix = parent + "/";
this.framework = framework;
this.config = config;
// make sure the parent node exists.
try {
if (framework.checkExists().forPath(parent) == null) {
framework.create().withMode(CreateMode.PERSISTENT).forPath(parent);
}
this.childrenCache = new PathChildrenCache(framework, parent, true);
this.childrenCache.start(StartMode.BUILD_INITIAL_CACHE);
} catch (Exception e) {
throw new RuntimeException("Failure while accessing Zookeeper for PStore: " + e.getMessage(), e);
}
}
示例8: getZkRangeStore
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
public ZkRangeStore getZkRangeStore(int clientIndex) {
String lockPath = "/snowflake/locks";
String storePath = "/snowflake/idstore";
CuratorFramework curatorFramework = ZkUtils.create("127.0.0.1:2181", 1000, 10000);
curatorFramework.start();
for (String client : clients) {
try {
curatorFramework.setData().forPath(ZKPaths.makePath(storePath, client), "0".getBytes());
} catch (Exception e) {
if (e instanceof KeeperException.NoNodeException) {
try {
curatorFramework.create().creatingParentsIfNeeded().forPath(storePath, "0".getBytes());
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
return new ZkRangeStore(clients.get(clientIndex), curatorFramework, lockPath, storePath, 1, TimeUnit.SECONDS, 0, 10);
}
示例9: getFlumeConfiguration
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
@Override
protected FlumeConfiguration getFlumeConfiguration() {
try {
CuratorFramework cf = createClient();
cf.start();
try {
byte[] data = cf.getData().forPath(basePath + "/" + getAgentName());
return configFromBytes(data);
} finally {
cf.close();
}
} catch (Exception e) {
LOGGER.error("Error getting configuration info from Zookeeper", e);
throw new FlumeException(e);
}
}
示例10: FileResourceService
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
/**
* Create a File-based repository service
* @param partitionData the partition data configuration
* @param partitionUrls the partition URL configuration
* @param curator the curator framework
* @param producer the kafka producer
* @param notifications the notification service
* @param idSupplier an identifier supplier for new resources
* @param async generate cached resources asynchronously if true, synchonously if false
* @throws IOException if the directory is not writable
*/
public FileResourceService(final Map<String, String> partitionData, final Map<String, String> partitionUrls,
final CuratorFramework curator, final Producer<String, String> producer, final EventService notifications,
final Supplier<String> idSupplier, final Boolean async) throws IOException {
super(partitionUrls, producer, curator, notifications, idSupplier, async);
requireNonNull(partitionData, "partition data configuration may not be null!");
RESERVED_PARTITION_NAMES.stream().filter(partitionData::containsKey).findAny().ifPresent(name -> {
throw new IllegalArgumentException("Invalid partition name: " + name);
});
this.partitionData = partitionData;
init();
}
示例11: curatorFramework
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
@Bean
public CuratorFramework curatorFramework() {
ZKConfig config = config();
if (config.useZooKeeperWaitTimePolicy()) {
return new RedirectorCuratorFramework(config);
}
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString(config.getZooKeeperConnection())
.connectionTimeoutMs(config.getZooKeeperConnectionTimeout())
.sessionTimeoutMs(config.getZooKeeperSessionTimeout())
.retryPolicy(new RetryNTimes(config.getZooKeeperRetryAttempts(), config.getZooKeeperRetryInterval()))
.compressionProvider(new GzipCompressionProvider());
return builder.build();
}
示例12: curatorFramework
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
@Bean(name = "curator-framework")
public CuratorFramework curatorFramework() {
return CuratorFrameworkFactory
.builder()
.connectString(
env.getProperty("rpc.server.zookeeper.connect.string"))
.sessionTimeoutMs(
Integer.parseInt(env.getProperty(
"rpc.server.zookeeper.session.timeout.ms",
"10000")))
.connectionTimeoutMs(
Integer.parseInt(env.getProperty(
"rpc.server.zookeeper.connection.timeout.ms",
"10000"))).retryPolicy(this.retryPolicy())
.aclProvider(this.aclProvider()).authorization(this.authInfo())
.build();
}
示例13: childEvent
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
ChildData childData = event.getData();
switch (event.getType()) {
case CHILD_ADDED:
createOrUpdateViewMeta(childData, false);
break;
case CHILD_UPDATED:
createOrUpdateViewMeta(childData, true);
break;
case CHILD_REMOVED:
deleteNode(childData);
break;
default:
break;
}
}
示例14: listenerPathChildrenCache
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
/**
* 設置子節點更改監聽
*
* @param path
* @throws Exception
*/
public boolean listenerPathChildrenCache(String path, BiConsumer<CuratorFramework, PathChildrenCacheEvent> biConsumer) {
if (!ObjectUtils.allNotNull(zkClient, path, biConsumer)) {
return Boolean.FALSE;
}
try {
Stat stat = exists(path);
if (stat != null) {
PathChildrenCache watcher = new PathChildrenCache(zkClient, path, true);
watcher.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
//該模式下 watcher在重連的時候會自動 rebuild 否則需要重新rebuild
watcher.getListenable().addListener(biConsumer::accept, pool);
if (!pathChildrenCaches.contains(watcher)) {
pathChildrenCaches.add(watcher);
}
// else{
// watcher.rebuild();
// }
return Boolean.TRUE;
}
} catch (Exception e) {
log.error("listen path children cache fail! path:{} , error:{}", path, e);
}
return Boolean.FALSE;
}
示例15: RulesxmlTozkLoader
import org.apache.curator.framework.CuratorFramework; //導入依賴的package包/類
public RulesxmlTozkLoader(ZookeeperProcessListen zookeeperListen, CuratorFramework curator,
XmlProcessBase xmlParseBase) {
this.setCurator(curator);
// 獲得當前集群的名稱
String schemaPath = zookeeperListen.getBasePath();
schemaPath = schemaPath + ZookeeperPath.ZK_SEPARATOR.getKey() + ZookeeperPath.FLOW_ZK_PATH_RULE.getKey();
currZkPath = schemaPath;
// 將當前自己注冊為事件接收對象
zookeeperListen.addListen(schemaPath, this);
// 生成xml與類的轉換信息
parseRulesXMl = new RuleParseXmlImpl(xmlParseBase);
}