grizzly http服务器应该继续运行

use*_*420 11 grizzly

下面是启动Grizzly Http Server的代码.如果我按任意键,服务器就会停止.有没有办法让它保持活力.

Jetty有join()方法,它不会退出主程序.Grizzly还有类似的东西吗?

public static void main(String args){



ResourceConfig rc = new PackagesResourceConfig("com.test.resources");

        HttpServer httpServer = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
        logger.info(String.format("Jersey app started with WADL available at "
                        + "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...",
                        BASE_URI, BASE_URI));

        System.in.read();
        httpServer.stop();

        }
Run Code Online (Sandbox Code Playgroud)

根据上面的代码,如果你点击任何键,服务器就会停止.我想让它继续运行.当我真的想要停止服务器时,我会杀死进程.主要方法不应该终止.

谢谢

小智 24

我使用了一个关机钩子.这是一个代码示例:

public class ExampleServer {
private static final Logger logger = LoggerFactory
        .getLogger(ExampleServer.class);

public static void main(String[] args) throws IOException {
    new Server().doMain(args);
}

public void doMain(String[] args) throws IOException {
    logger.info("Initiliazing Grizzly server..");
    // set REST services packages
    ResourceConfig resourceConfig = new PackagesResourceConfig(
            "pt.lighthouselabs.services");

    // instantiate server
    final HttpServer server = GrizzlyServerFactory.createHttpServer(
            "http://localhost:8080", resourceConfig);

    // register shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            logger.info("Stopping server..");
            server.stop();
        }
    }, "shutdownHook"));

    // run
    try {
        server.start();
        logger.info("Press CTRL^C to exit..");
        Thread.currentThread().join();
    } catch (Exception e) {
        logger.error(
                "There was an error while starting Grizzly HTTP server.", e);
    }
}

}
Run Code Online (Sandbox Code Playgroud)


nak*_*kib 1

服务器停止,因为您httpServer.stop()在输入流之后调用该方法。当执行到达时,System.in.read();它会挂起,直到您输入一个字母,然后移动到服务器停止处。

您可以只注释httpServer.stop(),因为该代码示例正是在按下某个键时挂断服务器。

但如果您想创建一个 Web 服务器实例,我建议您在 main() 中运行一个线程来启动 Grizzly Web 服务器的实例。