脚本检测Kafka和Zookeeper

  Java测试环境中Kafka最近总是自动停止,所有写了一个简单的脚本来监听Kafka和Zookeeper,其中Kafka监听端口为9092,Zookeeper监听端口为2181,脚本如下:

#!/bin/bash
#read -p "input port:" port 
export JAVA_HOME=/export/servers/jdk1.8.0_172
monitor=$(ss -lntup|grep 9092)
monitorzoo=$(ss -lntip|grep 2181)
if [ "$monitorzoo" ];then
        echo "up $(date +%F-%H:%M)" >> /test/monitorzoo-up.log
else
        echo "down $(date +%F-%H:%M)" >> /test/monitorzoo-down.log && /export/servers/zookeeper-3.4.12/bin/zkServer.sh start
fi
if [ "$monitor" ];then
        echo "up $(date +%F-%H:%M)" >> /test/monitor-up.log
else
        echo "down $(date +%F-%H:%M)" >> /test/monitor-down.log && /export/servers/kafka_2.11-1.1.0/bin/kafka-server-start.sh /export/servers/kafka_2.11-1.1.0/config/server.properties 1>/dev/null 2>&1 &
        #if [ $? ];then
        #       echo "kafka start ok $(date +%F-%H:%M)" >> /test/monitor-down.log
        #else
        #       echo "kafka start faild $(date +%F-%H:%M)" >> /test/monitor-down.log
        #fi
fi

  这里有个坑,我是想在定时任务中定时的监控两个端口的运行状态,若端口正常监听则输出日志,若不正常则启动服务。手动运行脚本时,不需要加JAVA的环境变量,因为当前shell已定义了JAVA的环境变量(在/etc/profile中),在手动执行脚本时默认已经定义好了JAVA的环境。而在定时任务中运行脚本时会新启动shell并未定义JAVA的环境变量,所以脚本中一定要定义JAVA的环境变量,不然会启动失败,因为Kafka和Zookeeper都是依赖于JAVA环境的。

posted @ 2019-04-10 20:43 readygood 阅读(...) 评论(...) 编辑 收藏