需求
將spring boot項目編譯成jar,注冊為windows系統服務
實現方式
在網上了解到,winsw這個開源項目,去github看了下,作者常年維護更新,文檔齊全,擁躉不少,自己寫了個小demo體驗了下還不錯,然后又運行了一個晚上,沒啥問題,遂決定采用它
開源地址
- 源庫地址 [https://github.com/winsw/winsw]
- 教程所需示例文件地址[https://gitee.com/war110/test-winsw]
- 教程所需實力文件下載地址[https://gitee.com/war110/test-winsw/releases/tag/v1]
需要準備什么?
- 在releases下載這個軟件的本體,一個exe,一個配置的xml
- 一個可以正常運行的jar(我是寫了個自用的項目,每五秒輸出一次日志)
-
一個win7或者win10的操作系統
注:下載示意,我使用的版本是2.11.0
只下載這兩個文件
怎么制作服務?
- 準備好寫好的jar,我這個是個剛初始化的spring boo項目,就額外加了個log日志的配置文件,代碼倉庫如下,exe和xml也在里面
- 配置xml文件,文件名改成和jar同名文件,例testexe.xml
<?xml version="1.0" encoding="UTF-8" ?>
<service>
<!-- 該服務的唯一標識 -->
<id>test-data</id>
<!-- 注冊為系統服務的名稱 -->
<name>SW test Data</name>
<!-- 對服務的描述 -->
<description>測試數據生成服務</description>
<!-- 將java程序添加到系統服務 -->
<executable>java</executable>
<!-- 執行的參數 -->
<arguments>-jar "testexe.jar"</arguments>
<!-- 日志模式 這種是exe幫忙收集產生的日志配置,如果jar自帶了log的話,也會輸出 -->
<!--<logpath>\logs</logpath>
<log mode="roll-by-size">
<!-- 歸檔文件大小,單位是KB -->
<sizeThreshold>3</sizeThreshold>
<keepFiles>8</keepFiles>
</log>-->
<!-- 日志模式 這種是exe不用幫忙收集產生的日志配置 因為jar自帶了log輸出那一套 -->
<log mode="none"></log>
</service>
-
將exe文件改名為跟jar同名的文件
部署示意圖 - 將服務注冊為系統服務
# cmd 管理員模式進入該文件夾內
# 輸入命令注冊為系統服務
testexe.exe install testexe.xml
# 看的success字樣說明已經注冊成功了
# 打開windows 服務管理界面,右鍵啟動這個服務,查看日志
- 卸載該服務
# cmd 管理員模式進入該文件夾內
# 停止該服務
testexe.exe stop
# 輸入命令卸載該服務
testexe.exe uninstall
擴展
服務命令
Your renamed WinSW.exe binary also accepts the following commands:
命令 | 描述 |
---|---|
[install] | Installs the service 安裝服務. |
[uninstall] | Uninstalls the service. 卸載服務 |
[start] | Starts the service. 啟動服務 |
[stop] | Stops the service. 停止服務 |
[restart] | Stops and then starts the service.重啟服務 |
[status] | Checks the status of the service. 查看服務狀態 |
[refresh] | Refreshes the service properties without reinstallation.無需重新安裝即可刷新服務屬性 |
[customize] | Customizes the wrapper executable.自定義包裝器可執行文件 |
以下是官方寫的 文檔地址
[https://github.com/winsw/winsw/blob/v3/docs/cli-commands.md]