背景
最近基于微服务的思想,使用Spring Boot开发了一个产品。产品开发完成,一开始部署的时候,采用的就是jar包的形式。这种形式存在两个缺点:一是服务启动后DOS窗口一直处于打开状态,二是不能开机启动。产品经理不能接受这种形式,要求注册成Windows服务。
我的环境
Spring Boot 1.5.9.RELEASE
JDK1.8
Win7
寻找解决方案
sc create
sc create 英文|拼音服务名称 binpath= "要注册成windows服务的jar全路径" start= auto
这种方式可以注册成windows服务,但是不能正常启动,会报一种1053的错误
1053.png
研究了好长时间,终究是没有解决,只好另谋它路。
procrun
procrun是apache的一个开源的将jar注册成windows服务的小工具,试了试,因为不能指定spring boot jar包的运行时配置文件即--spring.config.location=application.properties,只能作罢。
winsw
winsw是一款可将可执行程序安装成Windows Service的开源小工具,百度网盘下载地址:https://pan.baidu.com/s/15WTymkS5UnVB4XyhW-ejhQ,要使用winsw,电脑上必须已经安装.NET framework。
为了方便,将打包的项目jar和winsw放在同一目录,将winsw-2.1.2-bin.exe重命名为和xx.jar包同名xx.exe。在当前目录下新建一个xml文件:xx.xml,内容如下:
<service>
<id>xx</id>
<name>xx</name>
<description>This service runs xx project.</description>
<executable>java</executable>
<arguments>-jar "xx.jar" [附加参数]</arguments>
<logmode>rotate</logmode>
</service>
我的配置文件是这样的
<?xml version="1.0" encoding="UTF-8"?>
<service>
<id>Hello</id>
<name>Hello</name>
<description>Hello</description>
<executable>java</executable>
<arguments>-jar "Hello.jar" --spring.config.location="application.properties"</arguments>
<logmode>rotate</logmode>
</service>
然后在当前文件中打开DOS窗口输入
# install安装windows服务
hello install
# 使用start命令启动服务
hello start
# 使用uninstall命令卸载服务;
hello uninstall
# 使用stop命令停止服务
hello stop
# 使用restart命令停止服务;
# 使用status命令查看当前服务的状态;
hello status
NSSM
winsw虽然能够解决我的需求,但是毕竟需要在目标机器上安装.NET framework,且目标机器环境各异,给实施人员增加了难度,有点小题大做了。
随后有找到了NSSM。
把下面的代码copy到一个bat文件中并进行响应的更改,同时保持nssm.exe与bat在统一目录下。
nssm install 英文服务名 JAVA_HOME\bin\java.exe
nssm set 英文服务名 AppParameters -jar spring boot jar --spring.config.location=使用的配置文件路径 -secret redacted
nssm set 英文服务名 AppDirectory %cd%\bin\edu-core-service
nssm set 英文服务名 AppStdout 输出日子路径\log.log
nssm set 英文服务名 AppStderr 错误日志路径\err.log
nssm set 英文服务名 AppStopMethodSkip 6
nssm set 英文服务名 AppStopMethodConsole 1000
nssm set 英文服务名 AppThrottle 5000
nssm start 英文服务名
总结
最后在尝试了多种方案的失败之后,终于找到了可以解决我的需求的方案NSSM。其他的方案可能也能将jar注册成windows服务,只是不适合我的需求而已。









网友评论