美文网首页
centos,ubuntu 注册java服务

centos,ubuntu 注册java服务

作者: 只想做个俗人_贪财_好色 | 来源:发表于2023-03-16 11:20 被阅读0次

注册脚本

注册服务路径:

  • ubuntu : /lib/systemd/system/${serviceName}.service
  • centos : /usr/lib/systemd/system/${serviceName}.service

ubuntu 为例:

#!/bin/bash

basepath=$(cd `dirname $0`; pwd)
serviceName=$1
serviceFile=/lib/systemd/system/${serviceName}.service
deployPath=${basepath}/deploy.sh
if [ ! -f ${jarPath}  ];then
  echo "没有找到jar包"
  exit 1
fi

if [ ! -f ${deployPath}  ];then
  echo "没有找到启动脚本"
  exit 1
fi

rm -rf ${serviceFile}

echo "[Unit]" >> ${serviceFile}
echo "Description=java service" >> ${serviceFile}
echo "[Service]" >> ${serviceFile}
echo "WorkingDirectory=${basepath}" >> ${serviceFile}
#需要有服务启动脚本
echo "ExecStart=${deployPath} start ${serviceName}" >> ${serviceFile}
echo "ExecStop=${deployPath} stop ${serviceName}" >> ${serviceFile}
echo "User=root" >> ${serviceFile}
echo "Type=forking" >> ${serviceFile}
echo "Restart=on-failure" >> ${serviceFile}
echo "RestartSec=10" >> ${serviceFile}
echo "[Install]" >> ${serviceFile}
echo "WantedBy=multi-user.target" >> ${serviceFile}

chmod 644 ${serviceFile}
chmod +x ${deployPath}

systemctl daemon-reload
systemctl enable ${serviceName}
systemctl restart ${serviceName}

echo "初始化完成,请使用systemctl start ${serviceName}启动服务"

java启动脚本 deploy.sh

#!/bin/bash

APP_NAME=$2.jar
SERVICE_NAME=$2
DIR=$(cd $(dirname "$0") && pwd )
JAVA_PATH=$JAVA_HOME/bin/java

usage() {
    echo "Usage: sh deploy.sh [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_PATH   -jar  $APP_NAME > $SERVICE_NAME.log 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



相关文章

网友评论

      本文标题:centos,ubuntu 注册java服务

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