在Linux中利用Service启动、停止jar,配置开机自启

1.切换目录到/etc/rc.d/init.d,并编辑文件

cd /etc/rc.d/init.d

vim test

2.编写启动脚本内容

#!/bin/bash
#chkconfig: 2345 10 90 
#description: test service ....

LANG=en_US.UTF-8 #设置编码utf-8
export LANG
export JAVA_HOME=/usr/java/jdk1.8.0_231-amd64
export JRE_HOME=/$JAVA_HOME/jre
export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar
export PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin

APP_NAME=/usr/local/project/test.jar

usage() {
    echo "Usage: 请输入正确的脚本命令 [start|stop|restart|status]"
    exit 1
}
 
is_exist(){
  pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}'` 
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}
 
start(){
  is_exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} is already running. pid=${pid}"
  else
    nohup java -jar ${APP_NAME} >/dev/null 2>&1 &
  fi
}
 
stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -9 $pid
  else
    echo "${APP_NAME} is NOT running"
  fi  
}
 
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is running. Pid is ${pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}
 
restart(){
  stop
  sleep 5
  start
}
 
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac

3.给予权限

chmod +x /etc/rc.d/init.d/test

4.添加到chkconfig

chkconfig --add test

5.查看是否添加到chkconfig

chkconfig --list

6.添加到开机自启

chkconfig test on

7.关闭开机自启

chkconfig test off

8.脚本操作命令示例

service test status  #查看状态

service test start #启动

service test stop #停止

service test restart #重启

你可能感兴趣的:(笔记)