我已成功将Jetty嵌入到Eclipse RCP应用程序中。 在我的RCP应用程序中,当用户单击某个按钮时,将打开一个浏览器并显示一些servlet页面。 jsp文件位于一个单独的目录中,它是一个angulajs Web应用程序。
当用户关闭RCP时,我试图从Eclipse UI插件关闭嵌入式Jetty服务器。服务器在名为Workshop
的类中启动,这是Web项目的一部分,因此我无法访问Server实例来自Eclipse UI Plugin的调用,server.stop()。我已尝试下面的代码,但是在静脉中。
1>将ShutdownHook配置为Workshop
类Web项目
server = new Server();
server.setConnectors(new Connector[] { connector });
server.setHandler(handlers);
server.start();
handlers.addHandler(new ShutdownHandler(server, "abc"));
server.setStopAtShutdown(true);
server.setGracefulShutdown(7_000);
ShutdownThread.getInstance().run();
2 - ;在我的Eclipse UI插件中,我添加了
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
URL url = new URL("http://localhost:" + resultPortNo + "/shutdown?token=" + shutdownCookie);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.getResponseCode();
logger.info("Shutting down " + url + ": " + connection.getResponseMessage());
} catch (SocketException e) {
// logger.debug("Not running");
// Okay - the server is not running
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
HtppUrlConnection抛出404-NotFound响应代码。所以Jetty服务器仍在运行。我们如何处理Eclipse UI插件中的嵌入式Jetty关闭。
我读了很多文章,但找不到我的问题的答案。
任何帮助都将不胜感激。谢谢。
答案 0 :(得分:0)
问题:每次调用jettyServer.stop时,都会抛出Interrupt Exception,并且jetty服务器继续运行。
解决方案:(1)在Servlet代码中添加带有守护程序线程的Executor Service以停止Jetty服务器
JettyShutdownServlet.js
-----------------------
ExecutorService pool = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setDaemon(true);
return thread;
}
});
pool.execute(new Runnable() {
@Override
public void run() {
if (null != jettyServer) {
try {
jettyServer.stop();
jettyServer.join();
} catch (Exception e) {
logger.info("Error when stopping Jetty: " + e.getMessage());
}
}
}
});
(2)在Jetty启动代码中添加servlet。
servletContextHandler.addServlet(new ServletHolder(new JettyShutdownServlet(server)), "/shutdown");
(3)将shutdownhook添加到Eclipse UI类
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
String shutdownurl = "http://localhost:" + resultPortNo + "/api/shutdown";
URL url = new URL(shutdownurl);
HttpURLConnection connection =(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
try {
connection.getResponseCode();
connection.disconnect();
} catch (SocketException e) {
// logger.debug("Not running");
// Okay - the server is not running
connection.disconnect();
}
} catch (Exception x) {
// exception during shutdown
Activator.error("Unable to shutdown Jetty Server.\n" + x.getMessage());
}
}
});
这解决了我的问题,希望对别人有所帮助。