2015-07-13 53 views
1

我已经通过在war文件中使用jetty嵌入式服务器来设置我的springboot项目。所以基本上,我的战争文件是一个可执行文件。如何正常关闭嵌入式码头服务器应用程序?

实现ServletContextInitializer

我设置主类:

@Configuration 
@EnableAutoConfiguration 
@ComponentScan 
public class CrawlerApplication implements ServletContextInitializer { 


    public static void main(final String[] args) { 
    SpringApplication.run(CrawlerApplication.class, args); 
    } 

    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
    servletContext.setInitParameter("mainComponentClass", "com.datalyst.crawler.component.CrawlerServiceTopComponent"); 
    } 
} 

然后我也有配置的Java文件

@Configuration 
public class CrawlerConfig { 

    @Bean 
    public EmbeddedServletContainerFactory embeddedServletContainerFactory(){ 
    return new JettyEmbeddedServletContainerFactory(8080); 
    } 

} 

这是的build.gradle

apply plugin: 'war' 

war { 
    baseName = 'crawler-service' 
    version = '0.0.1-SNAPSHOT' 
} 
configurations { 
    providedRuntime 
} 

bootRepackage{ 
    enabled = true 
} 

dependencies { 
    compile spec.external.springBootStarterWeb 
    compile 'org.springframework:spring-web:4.1.6.RELEASE' 

    providedRuntime("org.springframework.boot:spring-boot-starter-jetty") 
} 

现在,我设法构建它并通过执行以下命令启动服务器: nohup java -jar crawler-service-0.0.1-SNAPSHOT.war > crawler-service.log &

我使用nohup作为后台服务来运行它。

现在,当我想停止该程序时,我必须手动调查ps aux | grep java的对应PID,并通过执行sudo kill PID优雅地关闭。但我希望它会更好。

有什么办法可以正常关闭服务吗?例如,在启动时将STOP_PORT分配给该服务,然后使用该STOP_PORT停止它?

回答

1

下面是我用关机码头9的方法它是通过一个按钮叫上我的JSF应用程序:

public void shutdown() { 
    log.info("Stopping server ..."); 
    new Thread() { 
     @Override 
     public void run() { 
      try { 
       // workaround (maybe you can remove next line): 
       Thread.sleep(3000); 

       for (Handler handler : server.getHandlers()) { 
        handler.stop(); 
       } 
       server.stop(); 
       server.getThreadPool().join(); 
      } catch (Exception ex) { 
       System.out.println("Failed to stop Jetty"); 
      } 
     } 
    }.start(); 
} 
+1

谢谢,但我的服务没有任何交互UI。此外,“服务器”变量的类型是什么? server.stop是否调用ServletContextListener.onContextDestroyed()事件? –

+0

服务器的类型为:org.eclipse.jetty.server.Server。是的,该事件被调用,但我不知道它的server.stop()或handler.stop()。 – Stefan