Spark Framework:侦听服务器停止 [英] Spark Framework: Listen for server stop
问题描述
是否有一种方法可以在Spark框架关闭时进行监听以运行一些清理工作?例如,我想关闭我的ElasticSearch客户端.
Is there a way to listen for when Spark framework is shutting down, to run some cleanup? For example, I want to close out my ElasticSearch client.
推荐答案
正如@Martin Eden解释的一种方法是使用Runtime.getRuntime().addShutdownHook(...);
,但这与spark
服务器(码头)生命周期无关.实际上,您可以在不停止应用程序的情况下停止服务器,并且此关闭挂钩不会运行添加到runtime
的任何挂钩清理.因此,如果您停止应用程序,它将清理您的应用程序.
As @Martin Eden explains an approach is to use Runtime.getRuntime().addShutdownHook(...);
but this has nothing to do with spark
server (jetty) lifecycle. Actually, you could stop the server without stopping the app and this shutdown hook wouldn't run any hook-cleanup added to the runtime
. So this would cleanup your app if you stop it.
另一种选择是在Jetty中添加一个生命周期(托管)bean bean,并将关闭时的属性stop设置为true server.setStopAtShutdown(true);
.
Another option is to add a Lifecycle (managed) bean bean in Jetty and set the property stop at shutdown as true server.setStopAtShutdown(true);
.
EmbeddedServers.add(EmbeddedServers.Identifiers.JETTY, new MyJettyFactory());
static class MyJettyFactory implements EmbeddedServerFactory {
public EmbeddedServer create(Routes routeMatcher, StaticFilesConfiguration staticFilesConfiguration, boolean hasMultipleHandler) {
MatcherFilter matcherFilter = new MatcherFilter(routeMatcher, staticFilesConfiguration, false, hasMultipleHandler);
matcherFilter.init(null);
final Handler handler = new JettyHandler(matcherFilter);
return new EmbeddedJettyServer((maxThreads, minThreads, threadTimeoutMillis) -> {
final Server server = new Server();
server.setStopAtShutdown(true);
server.setStopTimeout(Duration.of(30, ChronoUnit.SECONDS).toMillis());
server.addBean(new ManagedObjects(new Managed() {
@Override
public void doStart() {
}
@Override
public void doStop() {
System.out.println("Good bye!");
}
}));
return server;
}, handler);
}
}
如果您未设置停止关机,则可以在spark服务停止时进行注册:
If you don't set a stop shutdown you could register when the spark service stops:
final Service ignite = Service.ignite();
Runtime.getRuntime().addShutdownHook(service::stop);
这篇关于Spark Framework:侦听服务器停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!