Play源代码分析:Server启动过程

开发 后端
Play!是一个full-stack(全栈的)Java Web应用框架,包括一个简单的无状态MVC模型,具有Hibernate的对象持续,一个基于Groovy的模板引擎,以及建立一个现代Web应用所需的所有东西。

Play是个Rails风格的Java Web框架,需要了解背景请看:

  1. Play Framework介绍1--主要概念
  2. Play Framework介绍2—Helloworld

如何调试请看此处。以下进入正题^_^

Server启动过程主要涉及三个地方:

  1. play.Play类:代表Play本身业务模型。
  2. play.server.Server类:负责服务器启动。
  3. play.classloading包:负责.java文件读取、编译和加载。

总体流程:

Play代码分析-Server.Main

Server.main为入口方法:

  1. public static void main(String[] args) throws Exception {  
  2.         …  
  3.         Play.init(root, System.getProperty("play.id"""));  
  4.         if (System.getProperty("precompile") == null) {  
  5.             new Server();  
  6.         } else {  
  7.             Logger.info("Done.");  
  8.         }  
  9.     } 

做两件事:

  1. Play.init
  2. 然后创建Server对象。

Play.init

  1. public static void init(File root, String id) {  
  2.  
  3. …  
  4.  
  5. readConfiguration();  
  6.  
  7.          Play.classes = new ApplicationClasses();  
  8.  
  9.         …  
  10.  
  11.         // Build basic java source path  
  12.         VirtualFile appRoot = VirtualFile.open(applicationPath);  
  13.         roots.add(appRoot);  
  14.         javaPath = new ArrayList<VirtualFile>(2);  
  15.         javaPath.add(appRoot.child("app"));  
  16.         javaPath.add(appRoot.child("conf"));  
  17.  
  18.         // Build basic templates path  
  19.         templatesPath = new ArrayList<VirtualFile>(2);  
  20.         templatesPath.add(appRoot.child("app/views"));  
  21.  
  22.         // Main route file  
  23.         routes = appRoot.child("conf/routes");  
  24.  
  25.         …  
  26.  
  27.         // Load modules  
  28.         loadModules();  
  29.  
  30.         …  
  31.  
  32.         // Enable a first classloader  
  33.         classloader = new ApplicationClassloader();  
  34.  
  35.         // Plugins  
  36.         loadPlugins();  
  37.  
  38.         // Done !  
  39.         if (mode == Mode.PROD ||preCompile() ) {  
  40.                 start();  
  41.             }  
  42.  
  43.         …  
  44.     } 

主要做:

  1. 加载配置
  2. new ApplicationClasses();加载app、views和conf路径到VirtualFile中,VirtualFile是Play内部的统一文件访问接口,方便后续读取文件
  3. 加载route
  4. 加载Module,Play的应用扩展组件。
  5. 加载Plugin,Play框架自身的扩展组件。
  6. 工作在产品模式则启动Play.

关键步骤为new ApplicationClasses(),执行computeCodeHashe(),后者触发目录扫描,搜索.java文件。相关过程简化代码如下:

  1. public ApplicationClassloader() {  
  2.         super(ApplicationClassloader.class.getClassLoader());  
  3.         // Clean the existing classes  
  4.         for (ApplicationClass applicationClass : Play.classes.all()) {  
  5.             applicationClass.uncompile();  
  6.         }  
  7.         pathHash = computePathHash();  
  8.        …  
  9.     } 
  1. int computePathHash() {  
  2.         StringBuffer buf = new StringBuffer();  
  3.         for (VirtualFile virtualFile : Play.javaPath) {  
  4.             scan(buf, virtualFile);  
  5.         }  
  6.         return buf.toString().hashCode();  
  7.     } 
  1. void scan(StringBuffer buf, VirtualFile current) {  
  2.         if (!current.isDirectory()) {  
  3.             if (current.getName().endsWith(".java")) {  
  4.                 Matcher matcher = Pattern.compile("\\s+class\\s([a-zA-Z0-9_]+)\\s+").matcher(current.contentAsString());  
  5.                 buf.append(current.getName());  
  6.                 buf.append("(");  
  7.                 while (matcher.find()) {  
  8.                     buf.append(matcher.group(1));  
  9.                     buf.append(",");  
  10.                 }  
  11.                 buf.append(")");  
  12.             }  
  13.         } else if (!current.getName().startsWith(".")) {  
  14.             for (VirtualFile virtualFile : current.list()) {  
  15.                 scan(buf, virtualFile);  
  16.             }  
  17.         }  
  18.     } 
Start流程

Play.Start过程

简化代码如下:

  1. public static synchronized void start() {  
  2.         try {  
  3.                         ...  
  4.             // Reload configuration  
  5.             readConfiguration();  
  6.  
  7.                         ...  
  8.               
  9.             // Try to load all classes  
  10.             Play.classloader.getAllClasses();  
  11.  
  12.             // Routes  
  13.             Router.detectChanges(ctxPath);  
  14.  
  15.             // Cache  
  16.             Cache.init();  
  17.  
  18.             // Plugins  
  19.             for (PlayPlugin plugin : plugins) {  
  20.                 try {  
  21.                     plugin.onApplicationStart();  
  22.                 } catch(Exception e) {  
  23.                     if(Play.mode.isProd()) {  
  24.                         Logger.error(e, "Can't start in PROD mode with errors");  
  25.                     }  
  26.                     if(e instanceof RuntimeException) {  
  27.                         throw (RuntimeException)e;  
  28.                     }  
  29.                     throw new UnexpectedException(e);  
  30.                 }  
  31.             }  
  32.  
  33.             ...  
  34.  
  35.             // Plugins  
  36.             for (PlayPlugin plugin : plugins) {  
  37.                 plugin.afterApplicationStart();  
  38.             }  
  39.  
  40.         } catch (PlayException e) {  
  41.             started = false;  
  42.             throw e;  
  43.         } catch (Exception e) {  
  44.             started = false;  
  45.             throw new UnexpectedException(e);  
  46.         }  
  47.     } 

关键步骤为执行Play.classloader.getAllClasses()加载app目录中的类型。简化代码如下:

  1. public List<Class> getAllClasses() {  
  2.         if (allClasses == null) {  
  3.             allClasses = new ArrayList<Class>();  
  4.  
  5.             if (Play.usePrecompiled) {  
  6.                 ...  
  7.             } else {  
  8.                 List<ApplicationClass> all = new ArrayList<ApplicationClass>();  
  9.  
  10.                 // Let's plugins play  
  11.                 for (PlayPlugin plugin : Play.plugins) {  
  12.                     plugin.compileAll(all);  
  13.                 }  
  14.  
  15.                 for (VirtualFile virtualFile : Play.javaPath) {  
  16.                     all.addAll(getAllClasses(virtualFile));  
  17.                 }  
  18.                 List<String> classNames = new ArrayList<String>();  
  19.                 for (int i = 0; i < all.size(); i++) {  
  20.                     if (all.get(i) != null && !all.get(i).compiled) {  
  21.                         classNames.add(all.get(i).name);  
  22.                     }  
  23.                 }  
  24.  
  25.                 Play.classes.compiler.compile(classNames.toArray(new String[classNames.size()]));  
  26.  
  27.                 for (ApplicationClass applicationClass : Play.classes.all()) {  
  28.                     Class clazz = loadApplicationClass(applicationClass.name);  
  29.                     if (clazz != null) {  
  30.                         allClasses.add(clazz);  
  31.                     }  
  32.                 }  
  33.                                 ...  
  34.             }  
  35.         }  
  36.         return allClasses;  
  37.     } 

主要步骤:

  1. plugin.compileAll,给所有plugin一次机会进行自定义编译。
  2. Play.classes.compiler.compile(classNames.toArray(new String[classNames.size()]));编译所有.java文件。编译后的.class存储在ApplicationClass中。内部使用了eclipse的JDT编译器。
  3. loadApplicationClass,取出ApplicationClass中的.class加入List<Class>中返回。

到此完成.java的加载。相关对象关系如下图:

Play代码分析

接着new Server()启动HTTP服务,监听请求

简化代码如下:

  1. public Server() {  
  2.              ...  
  3.         if (httpPort == -1 && httpsPort == -1) {  
  4.             httpPort = 9000;  
  5.         }  
  6.         ...  
  7.         InetAddress address = null;  
  8.         try {  
  9.             if (p.getProperty("http.address") != null) {  
  10.                 address = InetAddress.getByName(p.getProperty("http.address"));  
  11.             } else if (System.getProperties().containsKey("http.address")) {  
  12.                 address = InetAddress.getByName(System.getProperty("http.address"));  
  13.             }  
  14.  
  15.         } catch (Exception e) {  
  16.             Logger.error(e, "Could not understand http.address");  
  17.             System.exit(-1);  
  18.         }  
  19.           
  20.         ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(  
  21.                 Executors.newCachedThreadPool(), Executors.newCachedThreadPool())  
  22.         );  
  23.         try {  
  24.             if (httpPort != -1) {  
  25.                 bootstrap.setPipelineFactory(new HttpServerPipelineFactory());  
  26.                 bootstrap.bind(new InetSocketAddress(address, httpPort));  
  27.                 bootstrap.setOption("child.tcpNoDelay"true);  
  28.  
  29.                 if (Play.mode == Mode.DEV) {  
  30.                     if (address == null) {  
  31.                         Logger.info("Listening for HTTP on port %s (Waiting a first request to start) ...", httpPort);  
  32.                     } else {  
  33.                         Logger.info("Listening for HTTP at %2$s:%1$s (Waiting a first request to start) ...", httpPort, address);  
  34.                     }  
  35.                 } else {  
  36.                     if (address == null) {  
  37.                         Logger.info("Listening for HTTP on port %s ...", httpPort);  
  38.                     } else {  
  39.                         Logger.info("Listening for HTTP at %2$s:%1$s  ...", httpPort, address);  
  40.                     }  
  41.                 }  
  42.  
  43.             }  
  44.  
  45.         } catch (ChannelException e) {  
  46.             Logger.error("Could not bind on port " + httpPort, e);  
  47.             System.exit(-1);  
  48.         }  
  49.         ...  
  50.     } 

主要步骤:

  1. 设置端口,地址
  2. new ServerBootstrap,创建jboss netty服务器。Play1.1.1使用了netty作为底层通讯服务器。
  3. new HttpServerPipelineFactory(),设置netty所需的请求处理管道工厂。它负责当请求到达时提供处理者。
  4. bootstrap.bind(new InetSocketAddress(address, httpPort),绑定地址,端口。

到此万事具备,只等东风了…

原文链接:http://www.cnblogs.com/Chaos/archive/2011/04/17/2018500.html

【编辑推荐】

  1. Play Framework介绍:使用Eclipse开发和调试
  2. Play Framework介绍:Hello World
  3. Play Framework介绍:主要概念
  4. Java堆内存的10个要点
  5. “Java已死”简史
责任编辑:林师授 来源: Chaos的博客
相关推荐

2014-06-19 14:30:28

Android应用程序进程启动

2014-06-19 14:54:11

Android应用程序进程启动

2014-06-20 11:20:37

Android应用程序进程启动

2014-06-19 14:59:40

Android应用程序进程启动

2014-06-20 11:05:56

Android应用程序进程启动

2014-06-20 11:09:35

Android应用程序进程启动

2014-06-19 14:25:04

Android应用程序进程启动

2014-06-20 11:24:34

Android应用程序进程启动

2011-06-28 13:27:13

ARM Linux

2012-08-16 09:07:57

Erlang

2018-03-13 13:00:03

Linux运维启动分析

2011-07-28 10:34:38

Cocoa 程序 启动

2014-06-23 10:31:09

Android启动过程

2011-09-05 17:35:18

MTK启动过程RTOS

2009-12-03 10:00:46

Linux系统启动

2010-09-17 13:32:22

JVM.dll

2010-05-06 14:05:15

Unix系统

2021-07-02 06:34:53

Go语言sysmon

2009-07-08 11:25:36

jvm.dll

2020-04-20 21:30:51

Tomcat部署架构
点赞
收藏

51CTO技术栈公众号