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

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文件读取、编译和加载。

总体流程:

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(2);  
  15.         javaPath.add(appRoot.child("app"));  
  16.         javaPath.add(appRoot.child("conf"));  
  17.  
  18.         // Build basic templates path  
  19.         templatesPath = new ArrayList(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流程

简化代码如下:

  
 
 
 
  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 getAllClasses() {  
  2.         if (allClasses == null) {  
  3.             allClasses = new ArrayList();  
  4.  
  5.             if (Play.usePrecompiled) {  
  6.                 ...  
  7.             } else {  
  8.                 List all = new ArrayList();  
  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 classNames = new ArrayList();  
  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中返回。

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

接着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),绑定地址,端口。

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

网站栏目:Play源代码分析:Server启动过程
转载注明:http://www.shufengxianlan.com/qtweb/news33/426733.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联