美文网首页自动化运维
Centos 7将java jar包自定义开机启动服务

Centos 7将java jar包自定义开机启动服务

作者: Mracale | 来源:发表于2021-12-17 09:42 被阅读0次

    如果没有使用敏捷部署方式,每次服务器开机关机,都要通过 nohup java -jar hello.jar > /dev/null & 命令进行服务的启动,未免太过于繁琐,通过自定义服务的方式, 省去不少麻烦。

    1. 先上 jar包的启动脚本,
    #!/bin/bash
    JAVA_HOME=/usr/local/app/jdk1.8.0_191    
    PATH=$PATH:$JAVA_HOME/bin                     # shell脚本必须指定,因为脚本不会自动加载环境变量,不写的话导致出现此错误
    app='/usr/local/hello/hello.jar'    #jar包的决定路径
    args='-server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC'  #java程序启动参数,可不写
    LOGS_FILE=/dev/null                           # 把打印的日志扔进垃圾桶
     
    cmd=$1                                        #获取执行脚本的时候带的参数
    pid=`ps -ef|grep java|grep $app|awk '{print $2}'`                # 抓取对应的java进程
     
    startup(){
      aa=`nohup java -jar $args $app >> $LOGS_FILE 2>&1 &`
      echo $aa
    }
     
    if [ ! $cmd ]; then
      echo "Please specify args 'start|restart|stop'"
      exit
    fi
     
    if [ $cmd == 'start' ]; then
      if [ ! $pid ]; then
        startup
      else
        echo "$app is running! pid=$pid"
      fi
    fi
     
    if [ $cmd == 'restart' ]; then
      if [ $pid ]
        then
          echo "$pid will be killed after 3 seconds!"
          sleep 3
          kill -9 $pid
      fi
      startup
    fi
     
    if [ $cmd == 'stop' ]; then
      if [ $pid ]; then
        echo "$pid will be killed after 3 seconds!"
        sleep 3
        kill -9 $pid
      fi
      echo "$app is stopped"
    fi
    

    写好脚本之后,需要为脚本添加可执行权限

    chmod +x hello-service.sh

    1. 自定义开机启动命令

    2.1 进入到/etc/systemd/system/

    # vi hello-service.service
    
    [Unit]
    Description=hello-service
    after=network.target
     
    [Service]
    User=root
    Group=root
    Type=forking
    KillMode=process
    ExecStart=/bin/sh /usr/local/hello/hello-service.sh start
    ExecReload=/bin/sh /usr/local/hello/hello-service.sh restart
    ExecStop=/bin/sh /usr/local/hello/hello-service.sh stop
    PrivateTmp=true
     
    [Install]
    WantedBy=multi-user.target  
    

    2.2 添加执行权限

    chmod +x hello-service.service

    2.3 添加开机启动服务
    systemctl enable hello-service.service #添加开机启动服务

    systemctl start hello-service.service # 启动服务

    systemctl stop hello-service.service #关闭服务

    systemctl restart hello-service.service # 重启服务

    systemctl status hello-service.service #查看服务状态

    systemctl disable hello-service.service #取消开机启动

    相关文章

      网友评论

        本文标题:Centos 7将java jar包自定义开机启动服务

        本文链接:https://www.haomeiwen.com/subject/jrtifrtx.html