zookeeper

<dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.3</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
</dependency>

//建立该路径的监听事件
IZkChildListener iZkChildListener = new IZkChildListener() {
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                //currentChilds 路径列表,根据当前实例路径及总的路径列表,设置实例号
                refreshKernelObj(kernel_obj, taskPathFileName, parentPath, currentChilds);
            }
};
zkClient.subscribeChildChanges(subscribePath, iZkChildListener);//subscribePath 为 zookeeperGroup 分组     BasisConstants.ZOOKEEPER_BASE_PATH+"/"+businessObjName+"/"+group
//创建个临时路径,并触发监听事件
zkClient.createEphemeral(taskPath, DateUtils.getCurrDateTime());//taskPath 为实例的全路径(host ip pid taskName实例启动时创建的任务名)

 

/**
     * 在kernel_obj中对taskPathFileName的数据进行刷新,刷新的根据是parentPath和currentChilds
     * @param kernel_obj            注册内核
     * @param taskPathFileName      目标文件名称  格式为createZKTaskPathFileName()方法的返回值
     * @param parentPath            监控的地址
     * @param currentChilds         其他路径列表
     */
    public void refreshKernelObj(ConcurrentHashMap<String,Object> kernel_obj,String taskPathFileName,String parentPath, List<String> currentChilds){
        //获取总数和当前数量,并且设置到kernel中
        int count = 0;
        int currentIdx = 0;
        List<String> currentChilds_sort = new LinkedList<String>();
        currentChilds_sort.addAll(currentChilds);
        Collections.sort(currentChilds_sort);
        for(int i=0;i<currentChilds_sort.size();i++){
            String childPath = currentChilds_sort.get(i);
            try{
                String taskName_tmp = childPath.substring(childPath.lastIndexOf(BasisConstants.SPLIT_TASKNAME)+9);//jobId_i
                String businessObjName = childPath.substring(0,childPath.indexOf("_"));//businessObjName
                if(taskPathFileName.equals(childPath)){
                    currentIdx = count;
                }
                count++;
            }catch (Exception e){
                logger.error("内核刷新异常",e);
            }
        }
        kernel_obj.put(BasisConstants.KERNELOBJ_GLOBAL_TASK_COUNT, count+"");
        kernel_obj.put(BasisConstants.KERNELOBJ_GLOBAL_TASK_INDEX, currentIdx + "");//当前任务数
        String registerFlg = BasisConstants.registerFlg;
        if("true".equals(registerFlg)){
            kernel_obj.put(BasisConstants.KERNELOBJ_GLOBAL_REGISTER_PATH,parentPath+"/"+taskPathFileName);//注册地址
            kernel_obj.put(BasisConstants.KERNELOBJ_zkClient, zkClient);
        }
    }

 


******************************* 获取注册中心下interName该服务实例数

if(InetAddress.getByName(temp.split(":")[0]).isReachable(2500)){// ip:端口
    connectedSingal = new CountDownLatch(1);
    zooKeeper = new ZooKeeper(temp, ZookeeperConstants.SESSION_TIMEOUT, new ServerWatcher());//链接zookeeper org.apache.zookeeper.Watcher
    connectedSingal.await(ZookeeperConstants.CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); 
    return zooKeeper;
}
if(zooKeeper.exists(interName, false) != null){
    List<String> children = zooKeeper.getChildren(interName,false);
    String infoStr = "";
for (String child : children) {
infoStr = URLDecoder.decode(child);
}
String[] response = {interName,children.size()+"",infoStr};//获取注册中心下interName该服务实例数
return response;

 

private static String getHostNameForLiunx() {
    try {
        return (InetAddress.getLocalHost()).getHostName();
    } catch (UnknownHostException uhe) {
        logger.debug("UnknownHostException", uhe);
        String host = uhe.getMessage(); // host = "hostname: hostname"
        if (host != null) {
            int colon = host.indexOf(':');
            if (colon > 0) {
                return host.substring(0, colon);
            }
        }
        return "UnknownHost";
    }
}
public static String getHostName() {
    if (System.getenv("COMPUTERNAME") != null) {
        return System.getenv("COMPUTERNAME");
    } else {
        return getHostNameForLiunx();
    }
}
public static String getIp(){
    String hostname = getHostName();
    try {
        return InetAddress.getByName(hostname).getHostAddress();
    } catch (UnknownHostException e) {
        logger.debug("UnknownHostException", e);
    }
    return "UnknownHost";
}
public static String getPid(){
    String name = ManagementFactory.getRuntimeMXBean().getName();
    String pid = name.split("@")[0];
    return pid;
}

 

posted @ 2017-12-03 11:46  苍天一穹  阅读(155)  评论(0编辑  收藏  举报