部署jar包windows服務(wù)工具

背景

某個(gè)周末一個(gè)線上項(xiàng)目因?yàn)榉?wù)器自動(dòng)重啟導(dǎo)致了系統(tǒng)掛了,我們是通過(guò)jenkins部署的jar包所以需要手動(dòng)重啟項(xiàng)目,解決問(wèn)題后準(zhǔn)備調(diào)換部署方式讓項(xiàng)目隨系統(tǒng)自動(dòng)啟動(dòng),試用tomcat后發(fā)現(xiàn)啟動(dòng)慢,并且日常開(kāi)發(fā)springboot都是使用內(nèi)置tomcat啟動(dòng),如果要保持和部署方式保持一致(避免本地代碼執(zhí)行和部署方式不一致導(dǎo)致的bug),需要配置外部tomcat比較麻煩,所以決定還是以java -jar命令方式啟動(dòng)并注冊(cè)為window服務(wù)

項(xiàng)目地址:https://gitee.com/code2roc/deploy-jar-util

環(huán)境依賴

  • windows系統(tǒng)

  • 安裝framework4.0

  • 安裝jdk配置環(huán)境變量

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

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

功能介紹

工具包含【服務(wù)名稱】【jar包路徑】【部署端口】【執(zhí)行結(jié)果】【操作按鈕】五個(gè)部分

  • 服務(wù)名稱

對(duì)應(yīng)的就是安裝后windows服務(wù)的名字

  • jar包路徑

部署項(xiàng)目的jar文件物理路徑

  • 部署端口

默認(rèn)為空不指定使用配置文件中端口,指定后使用自定義端口

  • 執(zhí)行結(jié)果

顯示安裝/卸載/啟動(dòng)/關(guān)閉服務(wù)適輸出的操作日志

  • 操作按鈕

在進(jìn)行服務(wù)操作前必須將所有配置確定輸入后點(diǎn)擊保存配置按鈕

安裝/卸載/啟動(dòng)/停止四個(gè)按鈕對(duì)應(yīng)相關(guān)windows服務(wù)的操作

服務(wù)安裝后默認(rèn)停止?fàn)顟B(tài),需要手動(dòng)啟動(dòng),服務(wù)啟動(dòng)方式為自動(dòng)

點(diǎn)擊啟動(dòng)服務(wù)后會(huì)自動(dòng)彈出啟動(dòng)日志界面動(dòng)態(tài)刷新日志內(nèi)容,若關(guān)閉了日志窗口,則進(jìn)入deploylog文件夾查看deploy.out.log文件,每次啟動(dòng)項(xiàng)目該文件內(nèi)容自動(dòng)重置清除


Opearte1.png
Opearte2.png
Opearte3.png

實(shí)現(xiàn)介紹

window服務(wù)安裝

使用開(kāi)源組件winsw(https://github.com/winsw/winsw/),獲取編譯好的exe運(yùn)行文件和xml配置文件,調(diào)用cmd進(jìn)行相關(guān)命令操作,例如安裝操作如下所示,頁(yè)面相關(guān)配置保存讀取直接操作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;   // 注冊(cè)進(jìn)程結(jié)束事件  
            p.Start();
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
            p.StandardInput.AutoFlush = true;
            string strOuput = p.StandardOutput.ReadToEnd();
            txt_Result.Text = strOuput;
            //等待程序執(zhí)行完退出進(jìn)程
            p.WaitForExit();
            p.Close();
        }

服務(wù)狀態(tài)監(jiān)控

通過(guò)引入System.ServiceProcess程序集調(diào)用服務(wù)相關(guān)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)
                {
                    //服務(wù)運(yùn)行中允許停止
                    btn_StopService.Enabled = true;
                }
                else
                {
                    //服務(wù)未運(yùn)行允許卸載和啟動(dòng)
                    btn_UnstallService.Enabled = true;
                    btn_StartService.Enabled = true;
                }
            }
            else
            {
                //無(wú)此服務(wù)允許安裝
                btn_InstallService.Enabled = true;
            }

        }

啟動(dòng)日志顯示

使用定時(shí)器,不斷刷新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;
            //執(zhí)行事件
            timer.Tick += (s, e1) =>
            {
                RefreshLogContent();
            };
            //開(kāi)始執(zhí)行
            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();
        }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容