grizzly http server should keep running

亡梦爱人 提交于 2019-11-30 05:06:15

I use a shutdown hook. Here's a code example:

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);
    }
}

}

Try something like:

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

The server stops because you call the httpServer.stop() method after the input stream. When the execution reachs the System.in.read(); it hangs till you enter a letter and then moves on to the server stop.

You can just comment httpServer.stop() because that code example is exactly to hang up the server when a key is pressed.

But if you want to create a Webserver instance I would suggest that you run a Thread in main() that starts an instance of the Grizzly Webserver.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!