Java Code Examples for org.I0Itec.zkclient.ZkClient#writeData()

The following examples show how to use org.I0Itec.zkclient.ZkClient#writeData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConfigStateHolder.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
private static void syncConfigIfMiss(String profile,ZkClient zkClient){

	if(!zkClient.exists(ZK_ROOT_PATH)){
		zkClient.createPersistent(ZK_ROOT_PATH, true);
		return;
	}
	
	String parentPath = ZK_ROOT_PATH + "/" + profile;
	if(!zkClient.exists(parentPath)){
		zkClient.createPersistent(parentPath, true);
		return;
	}
	List<String> apps = zkClient.getChildren(parentPath);
	for (String app : apps) {
		parentPath = ZK_ROOT_PATH + "/" + profile + "/" + app + "/nodes";
		
		int activeNodeCount = zkClient.countChildren(parentPath);
		if(activeNodeCount == 0)continue;
		List<ConfigState> localCacheConfigs = configStates.get(app + "#" + profile);
		
		if(activeNodeCount > 0 && (localCacheConfigs == null || localCacheConfigs.size() < activeNodeCount)){
			zkClient.writeData(parentPath, NOTIFY_UPLOAD_CMD);
			logger.info("send cmd[{}] on path[{}]",NOTIFY_UPLOAD_CMD,parentPath);
		}
	}
}
 
Example 2
Source File: ConfigStateHolder.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
public void publishChangeConfig(Map<String, String> changeConfigs){
	if(changeConfigs.isEmpty())return;
	if(!SYNC_TYPE_HTTP.equals(syncType)){
		ZkClient zkClient = getZkClient(env);
		if(zkClient.countChildren(zkPath) == 0){
			return;
		}
		zkClient.writeData(zkPath, JsonUtils.toJson(changeConfigs));
	}else{
		waitingSyncConfigs.putAll(changeConfigs);
		List<ConfigState> list = configStates.get(appName + "#" + env);
		for (ConfigState configState : list) {
			configState.existWaitSyncConfig = true;
		}
	}
}
 
Example 3
Source File: IncrementIdGen.java    From SkyEye with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 利用zookeeper
 * @return
 */
@Override
public String nextId() {
    String app = this.registerDto.getApp();
    String host = this.registerDto.getHost();
    ZkClient zkClient = this.registerDto.getZkClient();
    String path = Constants.ZK_REGISTRY_ID_ROOT_PATH + Constants.SLASH + app + Constants.SLASH + host;
    if (zkClient.exists(path)) {
        // 如果已经有该节点,表示已经为当前的host上部署的该app分配的编号(应对某个服务重启之后编号不变的问题),直接获取该id,而无需生成
        return zkClient.readData(Constants.ZK_REGISTRY_ID_ROOT_PATH + Constants.SLASH + app + Constants.SLASH + host);
    } else {
        // 节点不存在,那么需要生成id,利用zk节点的版本号每写一次就自增的机制来实现
        Stat stat = zkClient.writeDataReturnStat(Constants.ZK_REGISTRY_SEQ, new byte[0], -1);
        // 生成id
        String id = String.valueOf(stat.getVersion());
        // 将数据写入节点
        zkClient.createPersistent(path, true);
        zkClient.writeData(path, id);
        return id;
    }
}
 
Example 4
Source File: LocalCacheUtil.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Notify resource changed.
 * 向zookeeper注册中心广播 notifyName 对应的资源改变
 * 
 * @param notifyName the resource name
 */
public static void notifyResourceChanged(String notifyName) {
    ZkClient zClient = getZkClient();
    Long nanoTime = System.nanoTime();
    String resourcePath = getResourcePath(notifyName);
    if (!zClient.exists(resourcePath)) {
        zClient.createPersistent(resourcePath, true);
    }
    zClient.writeData(resourcePath, nanoTime);
}
 
Example 5
Source File: ZkUtil.java    From java-study with Apache License 2.0 5 votes vote down vote up
/**
 * 更新参数,没有就新增
 * @param zk
 * @param path
 * @param data
 * @return
 */
public static boolean setData(ZkClient zk,String path,String data){
	boolean falg=false;
	if(zk.exists(path)){
	   zk.writeData(path, data);
	   falg=true;
	}
	return falg;
}
 
Example 6
Source File: ZclientNormal.java    From javabase with Apache License 2.0 5 votes vote down vote up
/**
 * @Description: zkClient主要做了两件事情。
 * @see:一件是在session loss和session expire时自动创建新的ZooKeeper实例进行重连。
 * @see:一件是将一次性watcher包装为持久watcher。
 * @see:后者的具体做法是简单的在watcher回调中,重新读取数据的同时再注册相同的watcher实例。
 */
private static void test() {
	final ZkClient zc = new ZkClient("123.56.118.135:2181");
	// 创建根节点
	/* Persistent与Ephemeral 就是持久化保存到本地和不持久化的区别 ,不能再临时节点下面创建子节点 */
	
	zc.createPersistent("/testroot");
	// zc.createEphemeral("/testroot");
	// 创建子节点
	zc.create("/testroot/node1", "node1", CreateMode.EPHEMERAL);
	zc.createPersistent("/testroot/node2");
	zc.create("/testroot/node2/test", "node1", CreateMode.EPHEMERAL);
	List<String> children = zc.getChildren("/");
	log.info("根节点下面的字节点个数" + children.size());
	
	// 获得子节点个数
	
	int chidrenNumbers = zc.countChildren("/testroot");
	log.info("子节点个数" + chidrenNumbers);
	
	zc.writeData("/testroot/node2/test", "给节点写数据");
	
	// 删除节点
	zc.delete("/testroot/node2/test");
	zc.delete("/testroot/node2");
	zc.delete("/testroot/node1");
	zc.delete("/testroot");
}
 
Example 7
Source File: PinotHelixResourceManagerTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private void modifyExistingInstanceConfig(ZkClient zkClient)
    throws InterruptedException {
  String instanceName = "Server_localhost_" + new Random().nextInt(NUM_INSTANCES);
  String instanceConfigPath = PropertyPathBuilder.instanceConfig(getHelixClusterName(), instanceName);
  Assert.assertTrue(zkClient.exists(instanceConfigPath));
  ZNRecord znRecord = zkClient.readData(instanceConfigPath, null);

  InstanceConfig cachedInstanceConfig = _helixResourceManager.getHelixInstanceConfig(instanceName);
  String originalPort = cachedInstanceConfig.getPort();
  Assert.assertNotNull(originalPort);
  String newPort = Long.toString(System.currentTimeMillis());
  Assert.assertTrue(!newPort.equals(originalPort));

  // Set new port to this instance config.
  znRecord.setSimpleField(InstanceConfig.InstanceConfigProperty.HELIX_PORT.toString(), newPort);
  zkClient.writeData(instanceConfigPath, znRecord);

  long maxTime = System.currentTimeMillis() + MAX_TIMEOUT_IN_MILLISECOND;
  InstanceConfig latestCachedInstanceConfig = _helixResourceManager.getHelixInstanceConfig(instanceName);
  String latestPort = latestCachedInstanceConfig.getPort();
  while (!newPort.equals(latestPort) && System.currentTimeMillis() < maxTime) {
    Thread.sleep(100L);
    latestCachedInstanceConfig = _helixResourceManager.getHelixInstanceConfig(instanceName);
    latestPort = latestCachedInstanceConfig.getPort();
  }
  Assert.assertTrue(System.currentTimeMillis() < maxTime, "Timeout when waiting for adding instance config");

  // Set original port back to this instance config.
  znRecord.setSimpleField(InstanceConfig.InstanceConfigProperty.HELIX_PORT.toString(), originalPort);
  zkClient.writeData(instanceConfigPath, znRecord);
}
 
Example 8
Source File: ZkConfigUtil.java    From zkconfigutil with Apache License 2.0 4 votes vote down vote up
public final synchronized void register(Class<?> cla,
		boolean isCreateIfNUll, String rootPath)
		throws NotRegistedException, InstantiationException,
		IllegalAccessException {
	// if (!cla.isAnnotationPresent(TypeZkConfigurable.class)) {
	// throw new NotRegistedException();
	// }
	final ZkClient zkClient;
	if ("".equals(this.globalZkServer)) {
		logger.error("please set globalZkServer or set typeZkConfigurable.useOwnZkServer()=false to use own zkserver system will exit!!!");
		System.exit(0);
	}
	zkClient = this.makeZkClient(this.globalZkServer);
	// String packagePath = cla.getPackage().getName();
	// packagePath = packagePath.replaceAll("\\.", "/");
	//
	// rootPath = this.makeZkPath(rootPath, packagePath);
	String path = this.makeZkPath(rootPath, cla.getName());

	path = path.replace("$", "/"); // inclass

	final Field[] fields = cla.getDeclaredFields();

	for (Field field : fields) {
		if (!field.isAnnotationPresent(FieldZkConfigurable.class))
			continue;
		logger.info("field : " + field.getName() + "   type : "
				+ field.getType().getSimpleName());
		FieldZkConfigurable fieldZkConfigurable = field
				.getAnnotation(FieldZkConfigurable.class);

		final String fieldPath = this.makeZkPath(path, field.getName());

		String value = zkClient.readData(fieldPath, true);
		logger.info(fieldPath + " : " + value);

		Class<? extends AbstractResolve> resolve = fieldZkConfigurable
				.resolve();
		Resolve resolveInstance;
		if (resolve == ReflectResolve.class) {
			resolveInstance = new ReflectResolve(cla, field);
		} else {
			resolveInstance = resolve.newInstance();
		}

		/**
		 * Dosen't have value
		 */
		if (value == null && !isCreateIfNUll) {
			continue;
		} else if (value == null && isCreateIfNUll) {
			zkClient.createPersistent(fieldPath, true);
			String defaultValue = resolveInstance.resolve();
			zkClient.writeData(fieldPath, defaultValue);
		} else {
			/**
			 * have value
			 */
			resolveInstance.dResolve(value);
		}

		/**
		 * for USR2 signal
		 */
		SignalHelper.mark(cla, fieldPath, resolveInstance,
				fieldZkConfigurable.dynamicUpdate());

		if (fieldZkConfigurable.dynamicUpdate()) {
			logger.info("dynamicUpdate " + fieldPath);
			zkClient.subscribeDataChanges(fieldPath, this);
			Updater.register(fieldPath, resolveInstance);
		}
	}
}