0%

Windows服务器后台启动jar包

背景

    windows服务器中,通过窗口启动jar包,每个窗口对应一个临时会话。当关闭CMD窗口时,启动的Java程序会立即终止,无法实现长期运行。

    将 JAR 包注册为 Windows 服务,可随系统启动自动运行,支持服务管理(启动 / 停止 / 重启)。

工具:WinSW(Windows Service Wrapper)

  1. 下载 WinSW:

    从 GitHub 仓库 下载最新版本(如 WinSW-x64.exe)。

  2. 配置服务:

    • 将 WinSW-x64.exe 重命名为 your-service-name.exe(例如 myapp-service.exe)。

    • 在同目录下创建配置文件 your-service-name.xml,内容示例:

      xml

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      <service>
      <id>MyAppService</id>
      <name>My Application Service</name>
      <description>后台运行我的 Java 应用</description>
      <!-- JDK 路径(可选,系统已配置 JAVA_HOME 可省略) -->
      <executable>java</executable>
      <!-- 启动参数(替换为你的 JAR 路径) -->
      <arguments>-jar C:\path\to\your-application.jar</arguments>
      <!-- 日志配置 -->
      <logpath>C:\path\to\logs</logpath>
      <logmode>rotate</logmode>
      </service>
  3. 安装并启动服务:

    在命令行(管理员权限)中执行:

    bash

    1
    2
    3
    4
    # 安装服务
    myapp-service.exe install
    # 启动服务
    myapp-service.exe start
  4. 服务管理命令:

    bash

    1
    2
    3
    4
    5
    6
    # 停止服务
    myapp-service.exe stop
    # 重启服务
    myapp-service.exe restart
    # 卸载服务
    myapp-service.exe uninstall