Java 如何优雅地关闭嵌入式jetty服务器应用程序?
我在war文件中使用jetty嵌入式服务器设置了springboot项目。所以基本上,我的war文件是一个可执行文件 我设置了实现ServletContextInitializer的主类:Java 如何优雅地关闭嵌入式jetty服务器应用程序?,java,spring,servlets,jetty,spring-boot,Java,Spring,Servlets,Jetty,Spring Boot,我在war文件中使用jetty嵌入式服务器设置了springboot项目。所以基本上,我的war文件是一个可执行文件 我设置了实现ServletContextInitializer的主类: @Configuration @EnableAutoConfiguration @ComponentScan public class CrawlerApplication implements ServletContextInitializer { public static void main(f
@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);
}
}
这是建筑,格雷德尔
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")
}
现在,我通过执行以下命令来构建它并启动服务器:
nohupjava-jarcrawler-service-0.0.1-SNAPSHOT.war>crawler-service.log&
我使用nohup作为后台服务运行它
现在,当我想停止该程序时,我必须手动研究ps aux | grep java
的对应PID,并通过执行sudo kill PID
优雅地关闭。但我希望它更好
有什么方法可以优雅地关闭服务吗?例如,在启动服务时为其分配STOP_端口,然后使用该STOP_端口停止服务 以下是我用来关闭Jetty 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();
}
谢谢,但是我的服务没有任何交互界面。此外,“服务器”变量的类型是什么?server.stop是否调用ServletContextListener.onContextDestroyed()事件?服务器的类型为:org.eclipse.jetty.server.server。是的,该事件被调用,但我不知道它是server.stop()还是handler.stop()。