【问题标题】:Linux start-up script for java applicationjava应用程序的Linux启动脚本
【发布时间】:2011-09-28 02:13:55
【问题描述】:

我有使用此命令在 Linux 中运行的 Jar 文件:

java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13

在我们重新启动计算机时,谁能告诉我如何创建脚本并自动执行此过程?在 Windows 中我们使用服务,但是 linux 呢? 你能提供给我脚本和步骤吗,因为我是 Linux 的新手...

Linux : RHat, Ubuntu

谢谢

【问题讨论】:

    标签: java linux ubuntu startup redhat


    【解决方案1】:

    我将从这个模板开始,用于启动脚本,将 SCRIPT_HOME 重命名为正确的路径并在不带任何扩展名的情况下调用此文件,然后在 SSH 中运行此命令。

    chkconfig –add javaserver
    

    注意chkconfig 中的javaserver 是您在下面调用文件的方式(没有扩展名,否则它将不起作用)。

    #!/bin/bash
    #
    # javaserver: Startup script for Any Server Application.
    #
    # chkconfig: 35 80 05
    # description: Startup script for Any Server Application.
    
    SCRIPT_HOME=/var/java_server;
    export SCRIPT_HOME
    
    start() {
            echo -n "Starting Java Server: "
            $SCRIPT_HOME/run.sh start
            sleep 2
            echo "done"
    }
    
    stop() {
            echo -n "Stopping Java Server: "
            $SCRIPT_HOME/run.sh stop
            echo "done"
    }
    
    # See how we were called.
    case "$1" in
            start)
                    start
                    ;;
            stop)
                    stop
                    ;;
            restart)
                    stop
                    start
                    ;;
            *)
                    echo $"Usage: javaserver {start|stop|restart}"
                    exit
    esac
    

    现在这里是 run.sh 脚本(可以使用它来代替模板,但我发现将模板脚本设置为小且不可更改的链接到我的主脚本更容易,因此我再也不必触摸它了。

    下面的脚本是我发现的极少数脚本之一,它实际上可以在不关闭您当前正在运行的所有 java 程序的情况下重新启动 java 程序,这个脚本只针对它首先打开的程序,所以它永远不会犯任何错误,我从来没有失败过,在用户 root 上运行没问题。
    也永远在后台运行您的程序(无需保持 SSH 处于打开状态)。

    这是run.sh

    #!/bin/bash
    #
    # chkconfig: 345 99 05 
    # description: Java deamon script
    #
    # A non-SUSE Linux start/stop script for Java daemons.
    #
    # Set this to your Java installation
    JAVA_HOME=/usr/bin/
    
    scriptFile=$(readlink -fn $(type -p $0))                                        # the absolute, dereferenced path of this script file
    scriptDir=$(dirname $scriptFile)                                                    # absolute path of the script directory
    serviceNameLo="javaserver"                                                       # service name with the first letter in lowercase
    serviceName="JavaServer"                                                           # service name
    serviceUser="root"                                                                           # OS user name for the service
    serviceGroup="root"                                                                         # OS group name for the service
    applDir="/var/java_server"                                       # home directory of the service application
    serviceUserHome="/home/$serviceUser"                                      # home directory of the service user
    serviceLogFile="/var/log/$serviceNameLo.log"                            # log file for StdOut/StdErr
    maxShutdownTime=15                                                                     # maximum number of seconds to wait for the daemon to terminate normally
    pidFile="/var/run/$serviceNameLo.pid"                                        # name of PID file (PID = process ID number)
    javaCommand="java"                                                                       # name of the Java launcher without the path
    javaArgs="MyJavaAppClass"                                                                  # arguments for Java launcher
    javaCommandLine="$JAVA_HOME$javaCommand $javaArgs"   # command line to start the Java service application
    javaCommandLineKeyword="MyJavaAppClass"                                   # a keyword that occurs on the commandline, used to detect an already running service process and to distinguish it from others
    
    # Makes the file $1 writable by the group $serviceGroup.
    function makeFileWritable {
       local filename="$1"
       touch $filename || return 1
       chgrp $serviceGroup $filename || return 1
       chmod g+w $filename || return 1
       return 0; }
    
    # Returns 0 if the process with PID $1 is running.
    function checkProcessIsRunning {
       local pid="$1"
       if [ -z "$pid" -o "$pid" == " " ]; then return 1; fi
       if [ ! -e /proc/$pid ]; then return 1; fi
       return 0; }
    
    # Returns 0 if the process with PID $1 is our Java service process.
    function checkProcessIsOurService {
       local pid="$1"
       if [ "$(ps -p $pid --no-headers -o comm)" != "$javaCommand" ]; then return 1; fi
       grep -q --binary -F "$javaCommandLineKeyword" /proc/$pid/cmdline
       if [ $? -ne 0 ]; then return 1; fi
       return 0; }
    
    # Returns 0 when the service is running and sets the variable $pid to the PID.
    function getServicePID {
       if [ ! -f $pidFile ]; then return 1; fi
       pid="$(<$pidFile)"
       checkProcessIsRunning $pid || return 1
       checkProcessIsOurService $pid || return 1
       return 0; }
    
    function startServiceProcess {
       cd $applDir || return 1
       rm -f $pidFile
       makeFileWritable $pidFile || return 1
       makeFileWritable $serviceLogFile || return 1
       cmd="nohup $javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile"
       # Don't forget to add -H so the HOME environment variable will be set correctly.
       #sudo -u $serviceUser -H $SHELL -c "$cmd" || return 1
       su --session-command="$javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile" $serviceUser || return 1
       sleep 0.1
       pid="$(<$pidFile)"
       if checkProcessIsRunning $pid; then :; else
          echo -ne "\n$serviceName start failed, see logfile."
          return 1
       fi
       return 0; }
    
    function stopServiceProcess {
       kill $pid || return 1
       for ((i=0; i<maxShutdownTime*10; i++)); do
          checkProcessIsRunning $pid
          if [ $? -ne 0 ]; then
             rm -f $pidFile
             return 0
             fi
          sleep 0.1
          done
       echo -e "\n$serviceName did not terminate within $maxShutdownTime seconds, sending SIGKILL..."
       kill -s KILL $pid || return 1
       local killWaitTime=15
       for ((i=0; i<killWaitTime*10; i++)); do
          checkProcessIsRunning $pid
          if [ $? -ne 0 ]; then
             rm -f $pidFile
             return 0
             fi
          sleep 0.1
          done
       echo "Error: $serviceName could not be stopped within $maxShutdownTime+$killWaitTime seconds!"
       return 1; }
    
    function startService {
       getServicePID
       if [ $? -eq 0 ]; then echo -n "$serviceName is already running"; RETVAL=0; return 0; fi
       echo -n "Starting $serviceName   "
       startServiceProcess
       if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
       echo "started PID=$pid"
       RETVAL=0
       return 0; }
    
    function stopService {
       getServicePID
       if [ $? -ne 0 ]; then echo -n "$serviceName is not running"; RETVAL=0; echo ""; return 0; fi
       echo -n "Stopping $serviceName   "
       stopServiceProcess
       if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
       echo "stopped PID=$pid"
       RETVAL=0
       return 0; }
    
    function checkServiceStatus {
       echo -n "Checking for $serviceName:   "
       if getServicePID; then
        echo "running PID=$pid"
        RETVAL=0
       else
        echo "stopped"
        RETVAL=3
       fi
       return 0; }
    
    function main {
       RETVAL=0
       case "$1" in
          start)                                               # starts the Java program as a Linux service
             startService
             ;;
          stop)                                                # stops the Java program service
             stopService
             ;;
          restart)                                             # stops and restarts the service
             stopService && startService
             ;;
          status)                                              # displays the service status
             checkServiceStatus
             ;;
          *)
             echo "Usage: $0 {start|stop|restart|status}"
             exit 1
             ;;
          esac
       exit $RETVAL
    }
    
    main $1
    

    【讨论】:

      【解决方案2】:

      如果您想将应用程序作为 linux 守护进程(服务)运行,请查看 Java Wrapper:http://wrapper.tanukisoftware.com/doc/english/download.jsp

      也检查这个答案(适用于 windows,但对于 linux 有一点变化):How to install a Java application as a service

      【讨论】:

      • 我已经使用 tanuki 软件 2 年了。但是在我的情况下,我无法添加额外的库,因为这是生产服务器......
      【解决方案3】:

      虽然不建议对这样的项目进行 sudo,但可以通过以下方式完成:

      sudo crontab -e
      

      将以下内容放在 cron 中:

      @reboot java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13
      

      【讨论】:

      • 这似乎只有在您重新启动时才会发生...如何也立即启动?我无法重新启动服务器。
      【解决方案4】:

      嗯,首先你可能想编辑你的本地 IP,这是你提供的更多信息。无论如何只要打开一个新的文档类型这个

       #!/bin/bash
      
       #put your commands in here
      

      保存然后打开终端输入 chmod +x nameofscript

      我不确定 ubuntu,但在 arch 上我们有一个地方可以在启动时运行命令。 我的建议是转到系统-> 首选项-> 启动应用程序或类似的东西在我知道的那个菜单中。

      键入脚本的路径,即 /home/username/scrips/myawesomescript

      【讨论】:

      • 不确定为什么本地 IP 会成为安全问题...它显然位于 C 类子网(或其他变体)内,这意味着它位于某种类型的防火墙后面。没有人能够以这种方式访问​​它。
      【解决方案5】:

      基本上,您需要在 /etc/init.d 中创建一个小 shell 脚本,并创建指向 /etc/rc2.d 和 /etc/rc5.d 的符号链接。内容可能是这样的:

      #!/bin/sh
      if [ "$1" = start ] ; then
          cd /put_your_workdir_here
          /usr/bin/java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13 &
      fi
      

      请注意,您在后台启动程序(& 在命令行末尾)

      【讨论】:

      • 我已经尝试过你的方法,它失败了......不知道哪里错了
      【解决方案6】:

      您需要创建一个 unix shell 脚本文件,它会自动为您完成这项工作。 以下是创建脚本文件的步骤: http://www.linuxquestions.org/questions/linux-general-1/shell-script-for-jar-utility-769461/

      【讨论】:

        猜你喜欢
        • 2016-12-26
        • 2015-04-04
        • 1970-01-01
        • 2019-01-21
        • 2015-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多