将java项目写到服务中完成开机启动

    技术2022-07-16  85

    以testing.jar项目为例写一个启动脚本

    假如项目安装在/usr/local/testing目录下

    [root@froeasy ~]#cat /usr/local/testing/test_service.sh

    #!/bin/bash

    # 需要变更的参数

    java=/usr/java/jdk1.8.0_181/bin/java

    STARTUP="$java -server -XX:MetaspaceSize=640m -XX:MaxMetaspaceSize=640m -Xms1024m -Xmx4096m -Xmn512m -Xss1024k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC  -jar"

    JAR=`ls /usr/local/testing/*.jar -th |head -1`

     

    cd /usr/local/testing/

     

    function start () {

        nohup $STARTUP $JAR >> /usr/local/testing/log/testing.log 2>&1 &

        exit 0

    }

     

    function stop () {

        PID=`ps aux|grep "$JAR"|grep -v grep|awk '{print $2}'`

        if [ -z $PID ];then

            exit 0

        else

            kill -9 $PID

        fi

    }

     

    function reload () {

        PID=`ps aux|grep "$JAR"|grep -v grep|awk '{print $2}'`

        if [ -z $PID ];then

            exit 0

        else

            kill -1 $PID

        fi

    }

    case "$1" in

        start)

            start

            ;;

        stop)

            stop

            ;;

        reload)

            reload

            ;;

        restart)

            stop

            sleep 3

            start

            ;;

        *)

            echo "start|stop|reload|restart"

            ;;

    esac

     

    在写个服务文件:

    [root@froeasy ~]# cat /usr/lib/systemd/system/testing.service

    [Unit]

    Description=Java

    After=syslog.target network.target remote-fs.target nss-lookup.target

     

    [Service]

    User=root

    Group=root

    Type=forking

     

    ExecStart=/usr/local/testing/test_service.sh start

    ExecReload=/usr/local/testing/test_service.sh reload

    ExecStop=/usr/local/testing/test_service.sh stop

    PrivateTmp=true

     

    [Install]

    WantedBy=multi-user.target

     

    记得每次修改服务后要使用以下命令

    [root@froeasy ~]# systemctl daemon-reload

    常用命令

    [root@froeasy ~]# systemctl start testing

    [root@froeasy ~]# systemctl restart testing

    [root@froeasy ~]# systemctl stop testing

     

    Processed: 0.019, SQL: 10