package com.autonavi.tinfo.traffic.zookeeper;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.github.zkclient.IZkChildListener;
import com.github.zkclient.IZkStateListener;
import com.github.zkclient.ZkClient; public class DistributedZookeeper {
private static final Logger logger = LoggerFactory.getLogger(DistributedZookeeper.class);
private Lock lock = new ReentrantLock();// 锁对象
private int sessionTimeout;
private int connectionTimeout;
private String zkServerList;
// private String zkServerDir = "tmc-city-root-path";
private String subNode = "tmclr";
private String curPath;
private ZkClient zkClient;
private String[] resourcePath;
private String zookeeperPath; public String getZookeeperPath() {
return zookeeperPath;
} public void setZookeeperPath(String zookeeperPath) {
this.zookeeperPath = zookeeperPath;
} private ClassPathXmlApplicationContext context = null; private void start() {
if (context == null) {
context = new ClassPathXmlApplicationContext(resourcePath);
}
} private void destroy() {
if (context != null) {
// context.registerShutdownHook(); logger.info("destroyed current application!!!");
context.stop();
context.close();
context.destroy();
context.registerShutdownHook();
context = null;
}
} public void connect() throws Exception { if (this.zkClient != null) {
this.zkClient.close();
}
this.zkClient = new ZkClient(zkServerList, sessionTimeout, connectionTimeout); if (!zkClient.exists(zookeeperPath)) {
zkClient.createPersistent(zookeeperPath, null);
}
if (curPath == null) {
curPath = zkClient.createEphemeralSequential(zookeeperPath + "/" + subNode, "monitor".getBytes());
} try {
startWatchingTopicStatus();
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
logger.error("error occurs during sync data from zk");
System.exit(0);
}
Thread.sleep(2000);// */
handleMonitorNodeChange();
} public void startWatchingTopicStatus() {
ZkTopicStatusListener topicEventListener = new ZkTopicStatusListener();
ZkConnectedStatusListener connectedStatusListener = new ZkConnectedStatusListener();
try {
zkClient.subscribeChildChanges(zookeeperPath, topicEventListener);
zkClient.subscribeStateChanges(connectedStatusListener);
} catch (Exception e) {
logger.error(e.getMessage(), e);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
startWatchingTopicStatus();
} } public void handleMonitorNodeChange() throws Exception {
this.lock.lock();
try {
if (zkClient == null)
return;
if (!zkClient.exists(zookeeperPath)) {
zkClient.createPersistent(zookeeperPath, null);
} // 确认curPath是否真的是列表中的最小节点
List<String> childs = zkClient.getChildren(zookeeperPath);
if (childs == null || childs.size() == 0) {
// 创建子节点
curPath = zkClient.createEphemeralSequential(zookeeperPath + "/" + subNode, "monitor".getBytes());
childs = zkClient.getChildren(zookeeperPath); }
Collections.sort(childs); String thisNode = curPath.substring((zookeeperPath + "/").length());
int index = childs.indexOf(thisNode);
if (index < 0) {
curPath = zkClient.createEphemeralSequential(zookeeperPath + "/" + subNode, "monitor".getBytes());
childs = zkClient.getChildren(zookeeperPath);
Collections.sort(childs);
thisNode = curPath.substring((zookeeperPath + "/").length());
index = childs.indexOf(thisNode);
} if (index == 0) {
// 确实是最小节点
start();
} else {
destroy();
}
} finally {
this.lock.unlock();
}
} class ZkTopicStatusListener implements IZkChildListener { @Override
public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
handleMonitorNodeChange();
}
} class ZkConnectedStatusListener implements IZkStateListener { @Override
public void handleStateChanged(KeeperState state) throws Exception {
// TODO Auto-generated method stub ConnectedReadOnly
if (state.equals(KeeperState.SyncConnected) || state.equals(KeeperState.ConnectedReadOnly)) {
System.out.println("zookeeper start to be connected");
handleMonitorNodeChange();
} else if (state.equals(KeeperState.Disconnected)) {
destroy();
}
} @Override
public void handleNewSession() throws Exception {
// TODO Auto-generated method stub
} } public void stop() {
destroy();
if (zkClient == null) {
logger.warn("cannot shutdown already shutdown topic event watcher.");
return;
}
// stopWatchingTopicEvents();
zkClient.close();
zkClient = null;
} public void setZkServerList(String zkServerList) {
this.zkServerList = zkServerList;
} public int getSessionTimeout() {
return sessionTimeout;
} public void setSessionTimeout(int sessionTimeout) {
this.sessionTimeout = sessionTimeout;
} public int getConnectionTimeout() {
return connectionTimeout;
} public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
} public String[] getResourcePath() {
return resourcePath;
} public void setResourcePath(String[] resourcePath) {
this.resourcePath = resourcePath;
} public static void main(String[] args) throws Exception {
DistributedZookeeper statusMonitor = new DistributedZookeeper();
try {
if (args.length < 5) {
logger.warn("incomplete parameters.");
System.exit(0);
} // statusMonitor.setZkServerList("10.17.133.73:2181,10.17.133.73:2182,10.17.133.73:2183");
// statusMonitor.setConnectionTimeout(5000);
// statusMonitor.setSessionTimeout(5000);
// statusMonitor.setResourcePath(args); statusMonitor.setZkServerList(args[0]);
statusMonitor.setConnectionTimeout(Integer.valueOf(args[1]));
statusMonitor.setSessionTimeout(Integer.valueOf(args[2]));
statusMonitor.setZookeeperPath(args[3]);
statusMonitor.setResourcePath(Arrays.copyOfRange(args, 4, args.length)); statusMonitor.connect(); Executors.newSingleThreadExecutor().awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (Exception e) {
logger.error(e.toString(), e);
statusMonitor.stop();
System.exit(0);
} catch (OutOfMemoryError e) {
logger.error(e.toString(), e);
statusMonitor.stop();
System.exit(0);
}
} }

#!/bin/sh
#zookeeper address
zkAddress=100.69.209.30:2181,100.69.207.28:2181,100.69.193.87:2181
#connection timeout  in  Millseconds
connectTimeOut=60000
#session timeout  in  Millseconds
sessionTimeOut=60000
zookeeperPath="/tmc-city-path-aone"

x=`echo $0 | grep "^/"`
if test "${x}"; then
    dir=`dirname $0`
else
    pwdv=`pwd`
    dir=`dirname ${pwdv}/$0`
fi
dir=`readlink -m $dir`
echo "app location : "$dir

run="nohup /opt/taobao/java/bin/java  -Xms2G  -Xmx6G -Duser.dir=$dir/..  -cp ${dir}/../etc:${dir}/../lib/* com.autonavi.tinfo.traffic.zookeeper.DistributedZookeeper $zkAddress $connectTimeOut $sessionTimeOut $zookeeperPath classpath:ctx/**/*.xml"
log="nohup.out"
app_dir=`echo $dir|awk -F'/' '{print $(NF-1)}'`
len=`expr ${#app_dir} / 3`
app_dir_blur=`expr substr $app_dir 1 $len`
shutdown="kill `ps -ef|grep /opt/taobao/java/bin/java  |grep $dir| awk '{print $2}'`"
sd_rb="kill `ps -ef|grep /opt/taobao/java/bin/java  |grep $app_dir_blur| awk '{print $2}'`"

stopApp() {
    echo "starting stop ..."
    pid=`ps -ef|grep /opt/taobao/java/bin/java |grep $dir| awk '{print $2}'`
    echo $pid
    if [ ! $pid ]; then
        echo "not find process to kill"
    else
        kill -9 $pid
        echo "kill -9 $pid successfully"
    fi
}

case $1 in
    start)
        $run >> $log 2>&1 &
        chmod 744  $log
        ;;
    stop)
        #$shutdown
        stopApp
        ;;
    restart)
        $shutdown &&
        $run >> $log 2>&1 &
        ;;
    rb)
        $sd_rb &&
        $run >> $log 2>&1 &
        ;;
    *)
        echo "usage: run.sh [start|stop|restart]"
esac

zookeeper启动。的更多相关文章

  1. zookeeper启动报错(数据目录权限不对)

    zookeeper启动报错日志: 2016-11-16 11:19:43,880 [myid:3] - INFO [WorkerReceiver[myid=3]:FastLeaderElection@ ...

  2. zookeeper启动异常

    zookeeper启动报异常 java.io.EOFException  at java.io.DataInputStream.readInt(DataInputStream.java:392) 遇到 ...

  3. Zookeeper启动时报8080端口被占用

    zookeeper启动时报8080 端口被占用,导致启动失败.特别是服务器上部署了tomcat服务时需要注意. 通过查看zookeeper的官方文档,发现有3种解决途径: (1)删除jetty. (2 ...

  4. zookeeper启动报错处理记录

    zookeeper启动时正常,查看状态时出错 处理,通过 ./zkServer.sh status 报错Error contacting service. It is probably not run ...

  5. zookeeper启动配置

    zookeeper安装和配置详解 转载 2014年04月16日 14:36:31 16812 摘自:http://www.ibm.com/developerworks/cn/opensource/os ...

  6. Zookeeper启动失败:java.net.BindException: Address already in use

    错误日志如下: [hadoop@master zookeeper-3.4.5-cdh5.10.0]$ cat zookeeper.out 2018-05-15 01:29:21,036 [myid:] ...

  7. zookeeper启动

    Zookeeper启动总结1.实际项目用的是Linux,问题不大,本地开发学习用Windows,问题多多.2.Zookeeper3.5.1-alpha,和本地JDK1.7,有冲突,无法正常启动.3.Z ...

  8. macos brew zookeeper,安装后zookeeper启动失败?

    一.Zookeeper安装流程 执行如下安装命令: brew install zookeeper 执行截图如下: 安装后查看 zookeeper 安装信息(默认拉取最新版本) brew info zo ...

  9. Zookeeper启动过程

    在上一篇,我们了解了zookeeper最基本的配置,也从中了解一些配置的作用,那么这篇文章中,我们将介绍Zookeeper的启动过程,我们在了解启动过程的时候还要回过头看看上一篇中各个配置参数在启动时 ...

  10. zookeeper启动错误 transaction type: 2 error: KeeperErrorCode = NoNode for /hbase

    hbase伪分布式,与zookeeper同一台机器的时候,运行一段时间,启动zookeeper的时候,日志中有如下错误,导致无法启动zookeeper java.io.IOException: Fai ...

随机推荐

  1. GCD,用同步/异步函数,创建并发/串行队列

    队列  第一个参数:C语言字符串,标签 第二个参数: DISPATCH_QUEUE_CONCURRENT:并发队列 DISPATCH_QUEUE_SERIAL:串行队列 dispatch_queue_ ...

  2. c/c++ 函数指针 指针函数 数组的引用 指针数组 数组指针

    1.指针数组数组指针 引用数组 数组的引用 int *a[10] 指针数组 每一个元素都是一个指针 Int (*a)[10] 数组指针 P指向一个含有10个元素的数组 Int (&a)[10] ...

  3. JQuery源码解析(十)

    默认回调对象设计 不传入任何参数,调用add的时候将函数add到内部的list中,调用fire的时候顺序触发list中的回调函数: function fn1(val) { console.log('f ...

  4. IOS7 ~ Xcode5 制作 framework

    一.Framework 简介(Introduction to Framework Programming Guide) Mac OS X 扩展了 framework 的功能,让我们能够利用它来共享代码 ...

  5. 关于 xcode5 真机调试 的 no matching provisioning profiles found

    产生原因:在xcode5里面不一定是因为你的真机证书有问题,有可能是因为,项目本来在别的组里有会出现此bug 如果你出现上图的错误,只需要在此项目的***.xcodeproj 文件,然后右键选择“显示 ...

  6. webpack脚手架搭建(简单版)

    运行命令 安装依赖:npm install 运行项目:npm start 大致流程 npm init:新建 package.json 将需要的依赖模块加入 dependencies(生产环境) 和 d ...

  7. Array.prototype.indexOf

    arr.indexOf(searchElement[, fromIndex = 0]) Array.prototype.indexOf()

  8. Day18_集合第四天

    1.Map集合成员方法(掌握) 增加功能 V put(K key, V value) 当key在集合中不存在时,添加元素:当key在集合存在时候,替换元素 删除功能 void clear 清除所有键值 ...

  9. C&C++ recap

    大一时候学过C++,可惜忘得差不多了,之后也很少用过.当时使用的是windows系统,使用的还是visual C++.当时对计算机并不感冒,也没好好学.最近在R的学习中遇到瓶颈,觉得要捡起曾经的C/C ...

  10. JavaScript中的document.cookie的使用

    转:http://blog.csdn.net/liuyong0818/article/details/4807473 我们已经知道,在 document 对象中有一个 cookie 属性.但是 Coo ...