You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Java启动、停止Wildfly Application Server并检查启动状态

实现Wildfly服务器的启动、状态检查与停止功能

一、通过Java API启动Wildfly并验证状态

直接通过ProcessBuilder启动服务器进程,结合日志监控或CLI命令判断启动状态,是最直接可靠的方式。

1. 启动服务器+实时状态监控

以下代码实现启动、日志检测启动结果、自动部署应用及停止功能:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class WildflyManager {
    private Process serverProcess;

    // 启动Wildfly,传入Wildfly根目录路径
    public void startServer(String wildflyHome) throws IOException {
        // 根据系统选择启动脚本
        String startScript = System.getProperty("os.name").toLowerCase().contains("win")
                ? wildflyHome + "\\bin\\standalone.bat"
                : wildflyHome + "/bin/standalone.sh";

        ProcessBuilder pb = new ProcessBuilder(startScript);
        pb.redirectErrorStream(true); // 合并标准输出与错误输出,方便统一监听
        serverProcess = pb.start();

        // 开启线程监听服务器输出,判断启动状态
        new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(serverProcess.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                    // 匹配Wildfly启动成功的标志性日志(根据你的版本调整字符串)
                    if (line.contains("JBAS015874: WildFly Full") && line.contains("started in")) {
                        System.out.println("*服务器启动成功*");
                        // 启动成功后触发应用部署
                        deployApplication(wildflyHome);
                        break;
                    }
                    // 检测启动错误日志
                    if (line.contains("ERROR") && line.startsWith("JBAS")) {
                        System.err.println("*服务器启动失败:" + line);
                        stopServer();
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    // 用CLI命令部署应用
    private void deployApplication(String wildflyHome) throws IOException {
        String cliScript = System.getProperty("os.name").toLowerCase().contains("win")
                ? wildflyHome + "\\bin\\jboss-cli.bat"
                : wildflyHome + "/bin/jboss-cli.sh";

        // 替换为你的应用包路径
        ProcessBuilder pb = new ProcessBuilder(cliScript, "--connect", "command=deploy ./target/my-application.war");
        Process deployProcess = pb.start();

        // 打印部署输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(deployProcess.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }

    // 停止服务器(两种方式可选)
    public void stopServer() throws IOException, InterruptedException {
        if (serverProcess != null && serverProcess.isAlive()) {
            // 方式1:优雅停止(推荐)
            String wildflyHome = System.getProperty("wildfly.home");
            String cliScript = System.getProperty("os.name").toLowerCase().contains("win")
                    ? wildflyHome + "\\bin\\jboss-cli.bat"
                    : wildflyHome + "/bin/jboss-cli.sh";
            ProcessBuilder pb = new ProcessBuilder(cliScript, "--connect", "command=shutdown");
            Process stopProcess = pb.start();
            stopProcess.waitFor();

            // 方式2:强制终止(备用)
            // serverProcess.destroyForcibly();
            System.out.println("*服务器已停止*");
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        WildflyManager manager = new WildflyManager();
        // 替换为你的Wildfly实际路径
        String wildflyHome = "/opt/wildfly-26.1.3.Final";
        manager.startServer(wildflyHome);

        // 模拟应用运行时长,之后停止服务器
        Thread.sleep(60000);
        manager.stopServer();
    }
}

2. 解析CLI输出的正确姿势

之前解析CLI输出失败,可通过指定JSON格式输出,用JSON库(如Jackson)解析:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

// 检查服务器状态示例
private boolean checkServerStatus(String wildflyHome) throws IOException {
    String cliScript = System.getProperty("os.name").toLowerCase().contains("win")
            ? wildflyHome + "\\bin\\jboss-cli.bat"
            : wildflyHome + "/bin/jboss-cli.sh";

    ProcessBuilder pb = new ProcessBuilder(cliScript, "--connect", "--output-format=json", "command=:read-attribute(name=server-state)");
    Process statusProcess = pb.start();

    // 读取JSON格式输出
    BufferedReader reader = new BufferedReader(new InputStreamReader(statusProcess.getInputStream()));
    String jsonOutput = reader.lines().collect(Collectors.joining());

    // 解析JSON获取状态
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(jsonOutput);
    String serverState = node.get("result").asText();

    return "running".equals(serverState);
}

二、Bootable Jar方式修正方案

如果之前Bootable Jar启动失败,大概率是插件配置或依赖问题,以下是正确配置与代码:

1. Maven插件配置(pom.xml)

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-jar-maven-plugin</artifactId>
    <version>1.2.2.Final</version>
    <executions>
        <execution>
            <goals>
                <goal>package</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <feature-pack-location>wildfly@maven(org.jboss.universe:community-universe)#26.1.3.Final</feature-pack-location>
        <!-- 根据你的应用需求添加对应层,比如Web应用加web-server -->
        <layers>
            <layer>jaxrs-server</layer>
            <layer>web-server</layer>
        </layers>
        <start-mode>EMBEDDED</start-mode> <!-- 嵌入式启动,方便Java代码控制 -->
    </configuration>
</plugin>

2. Java代码启动嵌入式Bootable Jar服务器

import org.wildfly.core.embedded.EmbeddedServer;
import org.wildfly.core.embedded.EmbeddedServerFactory;

public class BootableJarController {
    public static void main(String[] args) throws Exception {
        EmbeddedServer server = EmbeddedServerFactory.create();
        server.start();

        if (server.isRunning()) {
            System.out.println("Bootable Jar服务器启动成功");
            // 应用已打包在Jar中,无需额外部署
        }

        // 运行后停止服务器
        Thread.sleep(60000);
        server.stop();
    }
}

三、关键注意事项

  • 确保Wildfly路径正确,Linux下需给启动脚本添加可执行权限(chmod +x standalone.sh jboss-cli.sh)。
  • 启动成功的日志字符串需匹配你的Wildfly版本,可先手动启动服务器查看日志确认。
  • 使用CLI连接时,若服务器未完全启动会连接失败,可添加重试逻辑(比如循环调用checkServerStatus直到成功或超时)。

内容的提问来源于stack exchange,提问作者Hvst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 17:53:31