1. 将 XXX 注册成 Windows 服务运行 -- 以Nacos为例

发布时间 2024-01-09 13:09:32作者: 即溶咖啡粉

众所周知,在 Windows 环境下想要启动 nacos 需要运行 bin 目录下的 startup.cmd。这样的启动方式需要保证 cmd 窗口一直开着,只要把这个窗口关掉,nacos 服务就停了。

所以为了避免人为的误关窗口,把 nacos 注册成一个 winserver 就是一个好的选择。这样不仅可以保证nacos一直在后台运行,还可以通过注册的服务名自定义开机自启动等。

下载 Windows Service Wrapper 工具

下载地址

https://github.com/winsw/winsw/releases

我下载的时候,最新可用版本是 v2.11.0 .
image

根据操作系统的位数不同,下载不同的 exe 文件,我这里下载的是64位的执行文件
![image]
(https://img2024.cnblogs.com/blog/3082200/202401/3082200-20240109124652070-237312529.png)

下载 exe 文件后

  • 将WinSW-x64.exe文件重命名位 nacos-service.exe,放在 nacos 的 bin 目录下
  • 创建配置文件 nacos-service.xml

nacos-service.xml 文件的内容如下:

<service>
  <!-- 唯一服务ID -->
  <id>nacos</id>
  <!-- 显示服务的名称 -->
  <name>Nacos Service</name>
  <!-- 服务描述 -->
  <description>Nacos服务</description>
  <!-- 日志路径,下面两个只能保留一个 -->
  <!-- 写死的方式,不推荐-->
  <logpath>你的nacos路径\nacos\bin\logs\</logpath>
  <!-- 动态的方式,推荐-->
  <logpath>%BASE%\logs\</logpath>
  <!-- 日志模式 -->
  <logmode>roll</logmode>
  <!-- 可执行文件的命令,下面两个只能保留一个 -->
  <!-- 写死的方式,不推荐-->
  <executable>你的nacos路径\nacos\bin\startup.cmd</executable>
  <!-- 动态的方式,推荐-->
  <executable>%BASE%\startup.cmd</executable>
  <!-- 停止可执行文件的命令,下面两个只能保留一个-->
  <!-- 写死的方式,不推荐-->
  <stopexecutable>你的nacos路径\nacos\bin\shutdown.cmd</stopexecutable>
  <!-- 动态的方式,推荐-->
  <stopexecutable>%BASE%\shutdown.cmd</stopexecutable>
</service>

打开cmd窗口(以管理员身份)进入 "你的nacos路径\nacos\bin" 下,运行以下命令,将 nacos 注册成 Windows 服务

nacos-service.exe install

查看nacos服务(快捷键: Ctrl+Shift+Esc)
image

如果需要卸载,打开cmd窗口(以管理员身份)进入到 nacos 的 bin 目录下,执行以下命令:

nacos-service.exe uninstall

启动/停止Nacos服务
选择Windows PowerShell(管理员)
image
输入如下命令启动 nacos 服务:

net start nacos
image

停止 nacos 服务:

net stop nacos
image