注:本文是为了配合《Spark内核设计的艺术 架构设计与实现》一书的内容而编写,目的是为了节省成本、方便读者查阅。书中附录C的内容都在本文呈现。
Jetty简介
Jetty是一个开源的,以Java作为开发语言的servlet容器。它的API以一组JAR包的形式发布。Jetty容器可以实例化成一个对象,因而迅速为一些独立运行的Java应用提供网络和web服务。要为Jetty创建servlet,就涉及ServletContextHandler的API使用。示例代码如下:
class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String msg = "Hello World!";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>" + msg + "</h1>");
response.getWriter().println("session=" + request.getSession(true).getId());
}
}
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);
// http://localhost:8080/hello
context.addServlet(new ServletHolder(new HelloServlet()), "/hello");
server.start();
server.join();
}
如果想更深入了解Jetty,请访问官网
http://www.eclipse.org/jetty/
JettyUtils
JettyUtils是Spark对于Jetty相关API的又一层封装,这里对其中一些主要类型和方法进行介绍。ServerInfo
功能描述:提供给Jetty服务器添加或移除ContextHandler,以及停止Jetty服务器的实现。
private[spark] case class ServerInfo(
server: Server,
boundPort: Int,
securePort: Option[Int],
private val rootHandler: ContextHandlerCollection) {
def addHandler(handler: ContextHandler): Unit = {
handler.setVirtualHosts(Array("@" + JettyUtils.SPARK_CONNECTOR_NAME))
rootHandler.addHandler(handler)
if (!handler.isStarted()) {
handler.start()
}
}
def removeHandler(handler: ContextHandler): Unit = {
rootHandler.removeHandler(handler)
if (handler.isStarted) {
handler.stop()
}
}
def stop(): Unit = {
server.stop()
// Stop the ThreadPool if it supports stop() method (through LifeCycle).
// It is needed because stopping the Se