grizzly http服务器应该继续运行

时间:2013-01-28 08:24:00

标签: 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();

        }

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

由于

3 个答案:

答案 0 :(得分: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);
    }
}

}

答案 1 :(得分:1)

尝试类似:

    try {
        server.start();
        Thread.currentThread().join();
    } catch (Exception ioe) {
        System.err.println(ioe);
    } finally {
        try {
            server.stop();
        } catch (IOException ioe) {
            System.err.println(ioe);
        }
    }

答案 2 :(得分:0)

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

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

但是如果你想创建一个Webserver实例,我建议你在main()中运行一个Thread来启动Grizzly Webserver的一个实例。

相关问题