基于Linux系统Java服务启停的通用shell

引言

应用程序的启停最为显著的特征是端口的占用情况,例如Nginx、Tomcat。除此之外也可以通过进程的文件信息判断进程启停情况。在Linux系统常用的两个命令分别为 lsofps。在应用的启停中通过监听端口去判断是否存在进行启停是更合理的一种方式。实际使用过程中都会使用到。

lsof用法

NAME
       lsof - list open files

SYNOPSIS
       lsof  [  -?abChKlnNOPRtUvVX  ]  [ -A A ] [ -c c ] [ +c c ] [ +|-d d ] [
       +|-D D ] [ +|-e s ] [ +|-E ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g [s]  ]  [
       -i  [i] ] [ -k k ] [ +|-L [l] ] [ +|-m m ] [ +|-M ] [ -o [o] ] [ -p s ]
       [ +|-r [t[m<fmt>]] ] [ -s [p:s] ] [ -S [t] ] [ -T [t] ] [ -u s ] [ +|-w
       ] [ -x [fl] ] [ -z [z] ] [ -Z [Z] ] [ -- ] [names]

DESCRIPTION
       Lsof  revision 4.89 lists on its standard output file information about
       files opened by processes for the following UNIX dialects:

            Apple Darwin 9 and Mac OS X 10.[567]
            FreeBSD 8.[234], 9.0, 10.0 and 11.0 for AMD64-based systems
            Linux 2.1.72 and above for x86-based systems
            Solaris 9, 10 and 11

       (See the DISTRIBUTION section of this manual page  for  information  on
       how to obtain the latest lsof revision.)

       An  open file may be a regular file, a directory, a block special file,
       a character special file, an executing text  reference,  a  library,  a
       stream  or  a  network  file  (Internet socket, NFS file or UNIX domain
       socket.)  A specific file or all the files in  a  file  system  may  be
       selected by path.

       Instead  of  a  formatted display, lsof will produce output that can be
       parsed by other programs.  See the -F, option description, and the OUT‐
       PUT FOR OTHER PROGRAMS section for more information.

       In  addition to producing a single output list, lsof will run in repeat
       mode.  In repeat mode it will produce output, delay,  then  repeat  the
       output  operation  until stopped with an interrupt or quit signal.  See
       the +|-r [t[m<fmt>]] option description for more information.


ps用法

NAME
       ps - report a snapshot of the current processes.

SYNOPSIS
       ps [options]

DESCRIPTION
       ps displays information about a selection of the active processes.  If you want a repetitive update of the selection and the displayed information, use top(1) instead.

       This version of ps accepts several kinds of options:

       1   UNIX options, which may be grouped and must be preceded by a dash.
       2   BSD options, which may be grouped and must not be used with a dash.
       3   GNU long options, which are preceded by two dashes.

       Options of different types may be freely mixed, but conflicts can appear.  There are some synonymous options, which are functionally identical, due to the many standards and ps
       implementations that this ps is compatible with.

       Note that "ps -aux" is distinct from "ps aux".  The POSIX and UNIX standards require that "ps -aux" print all processes owned by a user named "x", as well as printing all
       processes that would be selected by the -a option.  If the user named "x" does not exist, this ps may interpret the command as "ps aux" instead and print a warning.  This
       behavior is intended to aid in transitioning old scripts and habits.  It is fragile, subject to change, and thus should not be relied upon.

       By default, ps selects all processes with the same effective user ID (euid=EUID) as the current user and associated with the same terminal as the invoker.  It displays the
       process ID (pid=PID), the terminal associated with the process (tname=TTY), the cumulated CPU time in [DD-]hh:mm:ss format (time=TIME), and the executable name (ucmd=CMD).
       Output is unsorted by default.

       The use of BSD-style options will add process state (stat=STAT) to the default display and show the command args (args=COMMAND) instead of the executable name.  You can override
       this with the PS_FORMAT environment variable. The use of BSD-style options will also change the process selection to include processes on other terminals (TTYs) that are owned by
       you; alternately, this may be described as setting the selection to be the set of all processes filtered to exclude processes owned by other users or not on a terminal.  These
       effects are not considered when options are described as being "identical" below, so -M will be considered identical to Z and so on.

       Except as described below, process selection options are additive.  The default selection is discarded, and then the selected processes are added to the set of processes to be
       displayed.  A process will thus be shown if it meets any of the given selection criteria.

通过监听端口停止应用

使用lsof加关键词LISTEN获取端口,脚本如下:


#!/bin/bash
#author: sunz
#file name: killProcessByPort.sh
## 参数通过运行时传入
port1=$1
MSG="shutdown port %s at pid %s  %s \n"

killByPort(){
pids=$(lsof -i:$port1 | grep LISTEN | awk '{print $2}' |xargs)
pids_len=${#pids[*]}

if test $pids_len -ne 1
then
printf "port %s has been killed or not start yet. \n" $port1
fi

for pid in $pids; do
printf "shutdown port %s at pid %s  %s \n" $port1 $pid  'start'
kill -9 $pid
CheckKillResult $? $pid
done
}

CheckKillResult(){
result=$1
pid=$2
if test $result -eq 0
then 
printf "shutdown port %s at pid %s  %s \n" $port1 $pid  "successs"
else
printf "shutdown port %s at pid %s  %s \n" $port1 $pid  "failed"
fi
}

killByPort


# eg $killProcessByPort 9430

通用启动Java程序脚本

通过函数式编写启动Java程序脚本有如下优点:

  • 简化启动应用的脚本维护;
  • 统一维护一类程序的JVM参数;

脚本信息如下:

#!/bin/bash
#author: sunz
#file name: startJavaProcess.sh
## 参数通过运行时传入

APP=$1
startJavaProcess(){
  echo "start $APP "
  ## JVM参数基于Java8
  JVM=" -Xmx1344M -Xms1344M -Xmn448M -XX:MaxMetaspaceSize=256M -XX:MetaspaceSize=256M -XX:+UseConcMarkSweepGC -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 -XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses -XX:+CMSClassUnloadingEnabled -XX:+ParallelRefProcEnabled -XX:+CMSScavengeBeforeRemark "
  ## 特殊版本java的路径可以通过全路径制定
  nohup java $JVM -jar $APP >/dev/null 2>&1 &
  CheckStartResult $? $APP
}

CheckStartResult(){
result=$1
pid=$2
if test $result -eq 0
then 
printf "startup  %s  %s \n" $2 "successs"
else
printf "startup  %s  %s \n" $2 "failed"
fi
}

startJavaProcess

#  eg  $startJavaProcess zuul-boot-2.0.0-SNAPSHOT.jar

通过 ~/.bashrc 简化程序脚本

.bashrc 在用户登录时获取该文件的 aslias 等信息。维护人员可以通过别名简化程序脚本,增加维护效率。

.bash_profile 文件可以维护环境变量,也可以简化该脚本。

.bash_profile 修改过程如下:

# 编辑 bash_profile
# vi .bash_profile
SHELL_HOME="/home/sunz/文档/files/shell/cshell"
killProcessByPort='sh $SHELL_HOME/killProcessByPort.sh '
export killProcessByPort
startJavaProcess='sh $SHELL_HOME/startJavaProcess.sh '
export startJavaProcess

# 更新 bash_profile
# source .bash_profile

.bashrc 修改过程如下:

# 编辑 bash_profile
# vi .bash_profile
# 使用 alias 方法
SHELL_HOME="/home/sunz/文档/files/shell/cshell"
alias startJavaProcess='sh $SHELL_HOME/startJavaProcess.sh '
alias killProcessByPort='sh $SHELL_HOME/killProcessByPort.sh '

注意不同系统的文件名可能存在差异。

以user-gatewayin-svc为例子说明使用

服务部署路径信息 /app/user_projects/user-gatewayin-svc ,目录结构如下:

drwxr-xr-x 3 app sunz     4096 2月   1 13:40 config
-rw-r--r-- 1 app sunz       86 2月   1 13:47 start.sh
-rw-r--r-- 1 app sunz       19 12月  9 15:57 stop.sh
-rw-r--r-- 1 app sunz 57520835 1月   5 16:10 zuul-boot-2.0.0-SNAPSHOT.jar

其中 start.sh 内容如下;

$startJavaProcess "zuul-boot-2.0.0-SNAPSHOT.jar --spring.profiles.active=dev,dev-in"

其中 stop.sh 内容如下;

$killProcess 9450
posted @ 2023-07-28 09:47  落叶微风  阅读(13)  评论(0编辑  收藏  举报  来源