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