部署jar包windows服務工具

背景

某個週末一個線上項目因爲服務器自動重啓導致了系統掛了,我們是通過jenkins部署的jar包所以需要手動重啓項目,解決問題後準備調換部署方式讓項目隨系統自動啓動,試用tomcat後發現啓動慢,並且日常開發springboot都是使用內置tomcat啓動,如果要保持和部署方式保持一致(避免本地代碼執行和部署方式不一致導致的bug),需要配置外部tomcat比較麻煩,所以決定還是以java -jar命令方式啓動並註冊爲window服務

項目地址:https://gitee.com/code2roc/deploy-jar-util

環境依賴

  • windows系統

  • 安裝framework4.0

  • 安裝jdk配置環境變量

    jdk可以使用免安裝版本(1.8)點擊bat文件快速一鍵配置,下載地址如下

    https://yunpan.360.cn/surl_y83kPfrK6n7 (提取碼:c4f2)

功能介紹

工具包含【服務名稱】【jar包路徑】【部署端口】【執行結果】【操作按鈕】五個部分

  • 服務名稱

對應的就是安裝後windows服務的名字

  • jar包路徑

部署項目的jar文件物理路徑

  • 部署端口

默認爲空不指定使用配置文件中端口,指定後使用自定義端口

  • 執行結果

顯示安裝/卸載/啓動/關閉服務適輸出的操作日誌

  • 操作按鈕

在進行服務操作前必須將所有配置確定輸入後點擊保存配置按鈕

安裝/卸載/啓動/停止四個按鈕對應相關windows服務的操作

服務安裝後默認停止狀態,需要手動啓動,服務啓動方式爲自動

點擊啓動服務後會自動彈出啓動日誌界面動態刷新日誌內容,若關閉了日誌窗口,則進入deploylog文件夾查看deploy.out.log文件,每次啓動項目該文件內容自動重置清除

實現介紹

window服務安裝

使用開源組件winsw(https://github.com/winsw/winsw/),獲取編譯好的exe運行文件和xml配置文件,調用cmd進行相關命令操作,例如安裝操作如下所示,頁面相關配置保存讀取直接操作xml文件即可

  private void btn_InstallService_Click(object sender, EventArgs e)
        {
            string command = "deploy.exe install";
            StartCmd(AppDomain.CurrentDomain.BaseDirectory, command, FinishCommand);
        }
  public void StartCmd(String workingDirectory, String command, EventHandler FinsishEvent)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.EnableRaisingEvents = true;  // 啓用Exited事件  
            p.Exited += FinsishEvent;   // 註冊進程結束事件  
            p.Start();
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
            p.StandardInput.AutoFlush = true;
            string strOuput = p.StandardOutput.ReadToEnd();
            txt_Result.Text = strOuput;
            //等待程序執行完退出進程
            p.WaitForExit();
            p.Close();
        }

服務狀態監控

通過引入System.ServiceProcess程序集調用服務相關api

  public void InitOpStatus()
        {
            btn_InstallService.Enabled = false;
            btn_StartService.Enabled = false;
            btn_UnstallService.Enabled = false;
            btn_StopService.Enabled = false;
            var serviceControllers = ServiceController.GetServices();
            bool existservice = false;
            foreach (var service in serviceControllers)
            {
                if (service.ServiceName == txt_ServerName.Text)
                {
                    existservice = true;
                    break;
                }
            }
            if (existservice)
            {
                var server = serviceControllers.FirstOrDefault(service => service.ServiceName == txt_ServerName.Text);
                if (server.Status == ServiceControllerStatus.Running)
                {
                    //服務運行中允許停止
                    btn_StopService.Enabled = true;
                }
                else
                {
                    //服務未運行允許卸載和啓動
                    btn_UnstallService.Enabled = true;
                    btn_StartService.Enabled = true;
                }
            }
            else
            {
                //無此服務允許安裝
                btn_InstallService.Enabled = true;
            }

        }

啓動日誌顯示

使用定時器,不斷刷新deploylog\deploy.out.log日誌文件

   System.Windows.Forms.Timer timer;
        public LogForm()
        {
            InitializeComponent();
        }

        private void LogForm_Load(object sender, EventArgs e)
        {
            timer = new System.Windows.Forms.Timer();
            //1秒間隔
            timer.Interval = 1000;
            //執行事件
            timer.Tick += (s, e1) =>
            {
                RefreshLogContent();
            };
            //開始執行
            timer.Start();
        }


        public void RefreshLogContent()
        {
            string logPath = AppDomain.CurrentDomain.BaseDirectory + "deploylog\\deploy.out.log";
            string logContent = ReadFileContent(logPath);
            SetTextCallback d = new SetTextCallback(SetText);
            this.txt_Log.Invoke(d, new object[] { logContent });
        }

        public string ReadFileContent(string FileFullName)
        {
            if (File.Exists(FileFullName))
            {
                System.IO.FileStream fs = new System.IO.FileStream(FileFullName, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                string FileContent = "";
                try
                {
                    int fsLen = Convert.ToInt32(fs.Length);
                    byte[] heByte = new byte[fsLen];
                    int r = fs.Read(heByte, 0, heByte.Length);
                    FileContent = System.Text.Encoding.Default.GetString(heByte);
                }
                catch (Exception e)
                {
                    throw;
                }
                finally
                {
                    fs.Close();
                    fs.Dispose();
                }
                return FileContent;
            }
            else
            {
                return "";
            }

        }

        delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            txt_Log.Text = "";
            txt_Log.AppendText(text);
        }

        private void LogForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            timer.Stop();
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章