Linux start java service script

In an environment without automatic deployment, if you debug a java service, you need to kill the previous service each time and then start it again. Although the whole process only involves the following three commands , it can still be very crashing when debugging frequently.

ps -ef | grep myjar#myjar为服务名
kill -9 123456 #假设myjar的线程号为123456
nohup java -jar -Xms1024m -Xms2048m myjar.jar & # 习惯使用nohup从后台启动。-Xms为jvm 参数,&不要漏了

Encapsulated into a shell script as follows, named run.sh:

regular version

The jar package is ready in advance, here you only need to customize a specific script for this jar package

#1,获取myjar的进程号
PID=$(ps -ef|grep myjar| grep -v grep | awk '{print $2}')
#2,启动myjar的函数
start(){
    
    
        nohup java -jar -Xms1024m -Xms2048m myjar.jar -p -i &
}
#3,判断1中获取的PID是否存在,即判断myjar有没有启动
 if [ -z "$PID" ]
then
#4,日志
    echo "Sart the myjar directly "
#5,myjar之前没有启动的话,这里直接调用start函数
    start
else
#6,myjar之前启动过且进程依然存活,则kill掉,然后调用start函数
    echo "kill the existing myjar process firstly."
    kill -9 $PID
    echo " $PID has been killed"
    start
fi

Note: The permission of run.sh needs to be set to the state that the current user can execute. Since the kill command is involved in the script, it is recommended to execute it with root permission. For modifying file permissions, please learn the chmod command

Advanced version

Git is installed on the server, and the jar package is packaged through the mvn command. Each time before packaging, it is based on the latest code, so git pull needs to be executed. General operation and maintenance personnel will not give root permissions to git, so ordinary users need to execute run , But you need to add sudo before kill in run. The complete script is as follows:


#get the pid
PID=$(ps -ef|grep myjar| grep -v grep | awk '{print $2}')
start(){
    
    
  echo "======Ready to build project======"
  mvn clean package -Dmaven.test.skip=true #是否跳过unit test,true 为跳过
  # mvn clean package -P uat -Dmaven.test.skip=true #是否跳过unit test,true 为跳过.
  #-P指的是profile,uat指的是测试环境,pom中配置了profile才需要加上
  #-P 环境
  echo "======Build finished, ready to run======"
  nohup /usr/java/bin/java -jar -Xms1024m -Xms2048m target/myjar.jar  &
  tail -f nohup.out
}
echo "======Ready to get latest code from repository======"
git pull
if [ -z "$PID" ]
then
  echo "Sart the myjar directly "
  start
else
  echo "kill the existing myjar process firstly."
  sudo kill -9 $PID # sudo一定要加
  echo " $PID has been killed"
  start
fi

Next time you start, enter the directory where run.sh is located directly. /run.sh, if you don’t enter the directory, you need to bring the directory, such as ./x/x/x/run.sh

Guess you like

Origin blog.csdn.net/hongyinanhai00/article/details/105961711