grizzly http server should keep running

后端 未结 3 616
有刺的猬
有刺的猬 2020-12-29 10:49

Below is the code to start Grizzly Http Server. If I press any key the server stops. Is there any way to keep it alive.

Jetty has join() method, which will not exit

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 11:18

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

提交回复
热议问题