1.在linux上安装inotifywait实现文件监控

(1)  noitify下载地址:http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz

(2)  上传到服务器

(3)解压安装

tar -zxvf inotify-tools-3.14.tar.gz

进入到解压的文件中

cd inotify-tools-3.14

执行configure

./configure

make

先
make
再
make install

安装成功后在/usr/local/bin 下会有inotifywait 和 inotifywatch 命令。

2.编写shell脚本

这是我的目录,pd放java项目的jar包,pd_web放编译后的前端项目js之类的代码,script是放监听的脚本文件,和springboot的启动脚本文件

pd目录

pd_web目录

script目录

springboot.sh的内容用来控制jar包状态(里面用到了java命令需要自己提前装好jdk)

#! /bin/bash
# springboot的jar放同级目录下即可,只能有一个jar文件
CURRENT_PATH=/home/ftpuser/pd/
LOG=/home/ftpuser/script/springboot.log
JAR=$(find $CURRENT_PATH -maxdepth 1 -name "*.jar")
PID=$(ps -ef | grep $JAR | grep -v grep | awk '{ print $2 }')

case "$1" in
    start)
        if [ ! -z "$PID" ]; then
            echo "$JAR 已经启动,进程号: $PID"
        else
            echo -n -e "启动 $JAR ... \n"
            cd $CURRENT_PATH
        nohup java -Dloader.path=$CURRENT_PATH,resources,lib -jar $JAR >$LOG 2>&1 &
            if [ "$?"="0" ]; then
                echo "启动完成,请查看日志确保成功"
            else
                echo "启动失败"
            fi
        fi
        ;;
    stop)
        if [ -z "$PID" ]; then
            echo "$JAR 没有在运行,无需关闭"
        else
            echo "关闭 $JAR ..."
              kill -9 $PID
            if [ "$?"="0" ]; then
                echo "服务已关闭"
            else
                echo "服务关闭失败"
            fi
        fi
        ;;
    restart)
        ${0} stop
        ${0} start
        ;;
    kill)
        echo "强制关闭 $JAR"
        killall $JAR
        if [ "$?"="0" ]; then
            echo "成功"
        else
            echo "失败"
        fi
        ;;
    status)
        if [ ! -z "$PID" ]; then
            echo "$JAR 正在运行"
        else
            echo "$JAR 未在运行"
        fi
        ;;
  *)
    echo "Usage: ./springboot.sh {start|stop|restart|status|kill}" >&2
        exit 1
esac

watch_file_change.sh用来监听pd目录下的jar包是否有改变,当改变时自动调用springboot.sh 的restart命令

#!/bin/bash
src="/home/ftpuser/pd/"
log="/home/ftpuser/script/watch.log"
fileType="jar"
/usr/local/bin/inotifywait -mr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' -e close_write $src | while read DATE TIME DIR FILE; do

FILECHANGE=${DIR}${FILE}

if [[ $FILECHANGE =~ $fileType ]]
then
        echo “At ${TIME} on ${DATE}, file $FILECHANGE was change” >> $log
        /home/ftpuser/script/springboot.sh restart >> $log
fi
done

 

给.sh文件添加x执行权限

chmod u+x springboot.sh
chmod u+x watch_file_change.sh

执行watch_file_change.sh开启文件改变监听

./watch_file_change.sh

查看进程是否成功开启

[root@instance-g23bz0zz script]# ps aux|grep *

 

至此结束,

如果要单独运行jar包中的项目的话可以执行springboot.sh

./springboot.sh start

 

 

 

 

 

 

 

 

 

 

 

 

 

Logo

更多推荐