当前位置: > 其它学习 > 日常运维 >

Linux 监听端口并重启服务

时间:2020-04-11 18:30来源:linux.it.net.cn 作者:IT
本文以监听KAFKA端口是否挂掉,重启KAFKA服务为例子。

kafka 服务启动的前提是保证 zokeeper 服务已启动。关于详细配置不是本文的重点。

目录

1.编写 kafka 启动/停止脚本

2.编写 端口监听脚本

3.编辑 crontab 任务

1.编写 kafka 启动/停止脚本
vi /usr/local/kafka/kafka.service
#!/bin/bash
RETVAL=$?
KAFKA_HOME="/usr/local/kafka"

case "$1" in
start)
if [ -f $KAFKA_HOME/bin/kafka-server-start.sh ];
then
echo $"Starting kafka"
$KAFKA_HOME/bin/kafka-server-start.sh -daemon $KAFKA_HOME/config/server.properties
# $KAFKA_HOME/bin/kafka-server-start.sh  $KAFKA_HOME/config/server.properties
fi
;;
stop)
if [ -f $KAFKA_HOME/bin/kafka-server-stop.sh ];
then
echo $"Stopping Kafka"
$KAFKA_HOME/bin/kafka-server-stop.sh
fi
;;
*)
echo $"Usage: $0 {start|stop}"
exit 1
;;
esac

exit $RETVAL
编译脚本可执行

chmod +x /usr/local/kafka/kafka.service
2.编写 端口监听脚本
vi /usr/local/kafka/kafka/Listener_kafka_port_9077.sh
#!/bin/bash
ListeningPort=`netstat -an | grep ":9077" | awk '$1 == "tcp" && $NF == "LISTEN" {print $0}' | wc -l`
if [ $ListeningPort-eq 0 ]
then
{
echo "`date` : listener port is down">>/usr/local/kafka/kafka_down.log
# 如果9077端口down了,重启kafka服务,先停止删掉kafka的.lock 文件,再启动
/usr/local/kafka/kafka.service stop
sleep 3
/usr/local/kafka/kafka.service start
}
else
{
echo "`date` : 9077端口正常" >>/usr/local/kafka/kafka_ok.log
}
fi
编译脚本可执行

chmod +x /usr/local/kafka/kafka/Listener_kafka_port_9077.sh
3.编辑 crontab 任务
查看定时任务状态

service crond status
启动命令

service crond start
查看 crontab 任务有哪些定时任务

crontab -l
编写定时执行任务

crontab -e
crontab 配置规则请自行了解, 默认为1分钟执行一次,加入以下内容保证每5秒监听一次kafka 服务端口。

* * * * * /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 5; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 10; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 15; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 20; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 25; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 30; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 35; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 40; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 45; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 50; /usr/local/kafka/Listener_kafka_port_9077.sh
* * * * * sleep 55; /usr/local/kafka/Listener_kafka_port_9077.sh


(责任编辑:IT)
------分隔线----------------------------