最近部署了java程式,剛開始用shell來啟動,啟動過程不友好也不方便,也沒有守護進程。今年在整理資料的時候,發現了珍藏一套啟動指令碼。
挺方便的。記錄下。以免忘記
這是我的java程式結構
一個jar檔案,一個config設定檔 一個lib依賴包。
重點貼出 appStoreServer.py指令碼代碼
#!/usr/bin/pythonimport os, sys, time, commands_program = 'appStoreServer.jar'_daemon = 'appStoreServer.py'def getProgramPid(): result = commands.getoutput("ps aux | grep java \ | grep %s | grep -v grep | awk '{print $2}'" % _program) return resultdef getDaemonPid(): result = commands.getoutput("ps aux | grep python \ | grep '%s monitor' | grep -v grep | awk '{print $2}'" % _daemon) return resultdef startProgram(): p_pid = getProgramPid() if p_pid != '': print('It seems this program is already running...') else: print('Starting program...') if os.system('nohup java -Dfile.encoding=UTF-8 -server -Xms1024m -Xmx1024m -Xmn256m \-cp %s:config/:lib/* com.xxxx.Bootstrap >> log/stdio.log 2>&1 &' % _program) == 0: print('start program successfully and pid is ' + getProgramPid())def startDaemon(): d_pid = getDaemonPid() if d_pid != '': print('It seems this daemon is already running...') else: print('Starting daemon...') if os.system('nohup python %s monitor >> log/daemon.log 2>&1 &' % _daemon) == 0: print('start daemon successfully and pid is ' + getDaemonPid())def stopProgram(): p_pid = getProgramPid() if p_pid == '': print('It seems this program is not running...') else: os.system('kill ' + p_pid) print('program stopped')def stopDaemon(): d_pid = getDaemonPid() if d_pid == '': print('It seems daemon is not running...') else: os.system('kill ' + d_pid) print('daemon stopped')def monitor(): while 1: time.sleep(10) p_pid = getProgramPid() if p_pid == '': print('It seems this program is not running. Start it now!') startProgram()if __name__ == '__main__': if(len(sys.argv) == 2): args = sys.argv[1] else: args = raw_input('Enter args: ') logPath = os.path.curdir + os.sep + 'log' if not os.path.exists(logPath): os.mkdir(logPath) if args == 'start': startProgram() startDaemon() elif args == 'stop': stopDaemon() stopProgram() elif args == 'restart': stopDaemon() stopProgram() time.sleep(3) startProgram() startDaemon() elif args == 'monitor': monitor() else: print('nothing to do')
只需要修改你的jar 和main class 入口(這就是文中 com.xxx.bootstrap部分)。python調用了nuhop命令,退出終端也可以後台運行,挺方便的,重點的是還有daemo進程
修改了,開始啟動 java程式
關閉