资讯专栏INFORMATION COLUMN

Play framework源码解析 Part3:Play的初始化与启动

xuxueli / 2528人阅读

摘要:使用自建的类加载器主要是为了便于处理预编译后的字节码以及方便在模式下进行即时的热更新。

</>复制代码

  1. 注:本系列文章所用play版本为1.2.6

在上一篇中,我们分析了play的2种启动方式,这一篇,我们来看看Play类的初始化过程

Play类

无论是Server还是ServletWrapper方式运行,在他们的入口中都会运行Play.init()来对Play类进行初始化。那在解析初始化之前,我们先来看看Play类是做什么的,它里面有什么重要的方法。
首先要明确的一点是,Play类是整个Play framework框架的管理、配置中心,它存放了大部分框架需要的成员变量,例如id,配置信息,所有加载的class,使用的插件管理器等等。下图就是Play类中的方法列表。

这其中加注释的几个方法是比较重要的,我们下面便来从init开始一点点剖析Play类中的各个方法。

Play的初始化

</>复制代码

  1. public static void init(File root, String id) {
  2. // Simple things
  3. Play.id = id;
  4. Play.started = false;
  5. Play.applicationPath = root;
  6. // 加载所有 play.static 中的记录的类
  7. initStaticStuff();
  8. //猜测play framework的路径
  9. guessFrameworkPath();
  10. // 读取配置文件
  11. readConfiguration();
  12. Play.classes = new ApplicationClasses();
  13. // 初始化日志
  14. Logger.init();
  15. String logLevel = configuration.getProperty("application.log", "INFO");
  16. //only override log-level if Logger was not configured manually
  17. if( !Logger.configuredManually) {
  18. Logger.setUp(logLevel);
  19. }
  20. Logger.recordCaller = Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));
  21. Logger.info("Starting %s", root.getAbsolutePath());
  22. //设置临时文件夹
  23. if (configuration.getProperty("play.tmp", "tmp").equals("none")) {
  24. tmpDir = null;
  25. Logger.debug("No tmp folder will be used (play.tmp is set to none)");
  26. } else {
  27. tmpDir = new File(configuration.getProperty("play.tmp", "tmp"));
  28. if (!tmpDir.isAbsolute()) {
  29. tmpDir = new File(applicationPath, tmpDir.getPath());
  30. }
  31. if (Logger.isTraceEnabled()) {
  32. Logger.trace("Using %s as tmp dir", Play.tmpDir);
  33. }
  34. if (!tmpDir.exists()) {
  35. try {
  36. if (readOnlyTmp) {
  37. throw new Exception("ReadOnly tmp");
  38. }
  39. tmpDir.mkdirs();
  40. } catch (Throwable e) {
  41. tmpDir = null;
  42. Logger.warn("No tmp folder will be used (cannot create the tmp dir)");
  43. }
  44. }
  45. }
  46. // 设置运行模式
  47. try {
  48. mode = Mode.valueOf(configuration.getProperty("application.mode", "DEV").toUpperCase());
  49. } catch (IllegalArgumentException e) {
  50. Logger.error("Illegal mode "%s", use either prod or dev", configuration.getProperty("application.mode"));
  51. fatalServerErrorOccurred();
  52. }
  53. if (usePrecompiled || forceProd) {
  54. mode = Mode.PROD;
  55. }
  56. // 获取http使用路径
  57. ctxPath = configuration.getProperty("http.path", ctxPath);
  58. // 设置文件路径
  59. VirtualFile appRoot = VirtualFile.open(applicationPath);
  60. roots.add(appRoot);
  61. javaPath = new CopyOnWriteArrayList();
  62. javaPath.add(appRoot.child("app"));
  63. javaPath.add(appRoot.child("conf"));
  64. // 设置模板路径
  65. if (appRoot.child("app/views").exists()) {
  66. templatesPath = new ArrayList(2);
  67. templatesPath.add(appRoot.child("app/views"));
  68. } else {
  69. templatesPath = new ArrayList(1);
  70. }
  71. // 设置路由文件
  72. routes = appRoot.child("conf/routes");
  73. // 设置模块路径
  74. modulesRoutes = new HashMap(16);
  75. // 加载模块
  76. loadModules();
  77. // 模板路径中加入框架自带的模板文件
  78. templatesPath.add(VirtualFile.open(new File(frameworkPath, "framework/templates")));
  79. // 初始化classloader
  80. classloader = new ApplicationClassloader();
  81. // Fix ctxPath
  82. if ("/".equals(Play.ctxPath)) {
  83. Play.ctxPath = "";
  84. }
  85. // 设置cookie域名
  86. Http.Cookie.defaultDomain = configuration.getProperty("application.defaultCookieDomain", null);
  87. if (Http.Cookie.defaultDomain!=null) {
  88. Logger.info("Using default cookie domain: " + Http.Cookie.defaultDomain);
  89. }
  90. // 加载插件
  91. pluginCollection.loadPlugins();
  92. // 如果是prod直接启动
  93. if (mode == Mode.PROD || System.getProperty("precompile") != null) {
  94. mode = Mode.PROD;
  95. //预编译
  96. if (preCompile() && System.getProperty("precompile") == null) {
  97. start();
  98. } else {
  99. return;
  100. }
  101. } else {
  102. Logger.warn("You"re running Play! in DEV mode");
  103. }
  104. pluginCollection.onApplicationReady();
  105. Play.initialized = true;
  106. }

如上面的代码所示,初始化过程主要的顺序为:

加载所有play.static中记录的类

获取框架路径

读取配置文件

初始化日志

获取java文件、模板文件路径

加载模块

加载插件

若为prod模式进行预编译

我们来依次看看Play在这些过程中做了什么事情。

加载play.static

Play在初始化过程中会调用initStaticStuff()方法来检查代码目录下是否存在play.static文件,如果存在,那么就逐行读取文件中记录的类,并通过反射加载类中的静态初始化代码段。至于作用吗,不知道有什么用,这段代码的优先级太高了,早于初始化过程运行,若在初始化过程结束后运行还可以用来覆写Play类中的配置信息。或者自己写插件然后在play.static中初始化插件依赖?或者绑定新的数据源?

</>复制代码

  1. public static void initStaticStuff() {
  2. // Play! plugings
  3. Enumeration urls = null;
  4. try {
  5. urls = Play.class.getClassLoader().getResources("play.static");
  6. } catch (Exception e) {
  7. }
  8. while (urls != null && urls.hasMoreElements()) {
  9. URL url = urls.nextElement();
  10. try {
  11. BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
  12. String line = null;
  13. while ((line = reader.readLine()) != null) {
  14. try {
  15. Class.forName(line);
  16. } catch (Exception e) {
  17. Logger.warn("! Cannot init static: " + line);
  18. }
  19. }
  20. } catch (Exception ex) {
  21. Logger.error(ex, "Cannot load %s", url);
  22. }
  23. }
  24. }
获取框架路径

获取框架路径很简单,就是判断是用jar模式运行还是直接用文件运行,然后读取对应的路径

</>复制代码

  1. public static void guessFrameworkPath() {
  2. // Guess the framework path
  3. try {
  4. URL versionUrl = Play.class.getResource("/play/version");
  5. // Read the content of the file
  6. Play.version = new LineNumberReader(new InputStreamReader(versionUrl.openStream())).readLine();
  7. // This is used only by the embedded server (Mina, Netty, Jetty etc)
  8. URI uri = new URI(versionUrl.toString().replace(" ", "%20"));
  9. if (frameworkPath == null || !frameworkPath.exists()) {
  10. if (uri.getScheme().equals("jar")) {
  11. String jarPath = uri.getSchemeSpecificPart().substring(5, uri.getSchemeSpecificPart().lastIndexOf("!"));
  12. frameworkPath = new File(jarPath).getParentFile().getParentFile().getAbsoluteFile();
  13. } else if (uri.getScheme().equals("file")) {
  14. frameworkPath = new File(uri).getParentFile().getParentFile().getParentFile().getParentFile();
  15. } else {
  16. throw new UnexpectedException("Cannot find the Play! framework - trying with uri: " + uri + " scheme " + uri.getScheme());
  17. }
  18. }
  19. } catch (Exception e) {
  20. throw new UnexpectedException("Where is the framework ?", e);
  21. }
  22. }
读取配置文件

首先要说明一下,我们这里讨论的是在Play类初始化过程中的读取配置文件过程,为什么要指出这一点呢,因为配置文件读取后会调用插件的onConfigurationRead方法,而在初始化过程中,配置文件是优先于插件加载的,所以在初始化过程中插件的方法并不会生效。等到Play调用start方法启动服务器时,会重新读取配置文件,那时候插件列表已经更新完毕,会执行onConfigurationRead方法。
配置文件的读取和启动脚本中的解析方式基本一样,步骤就是下面几步:

读取application.conf,将其中的项全部加入Properties

将所有配置项用正则过滤找出真实配置名,并找出所用id的配置项替换

将配置项中的${..}替换为对应值

读取@include引用的配置

我们来看下play对${..}替换过程

</>复制代码

  1. Pattern pattern = Pattern.compile("${([^}]+)}");
  2. for (Object key : propsFromFile.keySet()) {
  3. String value = propsFromFile.getProperty(key.toString());
  4. Matcher matcher = pattern.matcher(value);
  5. StringBuffer newValue = new StringBuffer(100);
  6. while (matcher.find()) {
  7. String jp = matcher.group(1);
  8. String r;
  9. //重点是下面这个判断
  10. if (jp.equals("application.path")) {
  11. r = Play.applicationPath.getAbsolutePath();
  12. } else if (jp.equals("play.path")) {
  13. r = Play.frameworkPath.getAbsolutePath();
  14. } else {
  15. r = System.getProperty(jp);
  16. if (r == null) {
  17. r = System.getenv(jp);
  18. }
  19. if (r == null) {
  20. Logger.warn("Cannot replace %s in configuration (%s=%s)", jp, key, value);
  21. continue;
  22. }
  23. }
  24. matcher.appendReplacement(newValue, r.replaceAll("", ""));
  25. }
  26. matcher.appendTail(newValue);
  27. propsFromFile.setProperty(key.toString(), newValue.toString());
  28. }

可以看出除了${application.path}和${play.path},我们还可以通过使用参数和修改环境变量来添加可替换的值

初始化日志

Play的日志处理放在Logger类中,默认使用log4j作为日志记录工具,初始化过程的顺序如下

查找配置文件中是否有日志配置文件路径,存在跳至4

查找是否有log4j.xml,存在跳至4

查找是否有log4j.properties,存在跳至4

根据文件后缀使用对应的日志配置解析器

如果是测试模式则加上写入测试结果文件的Appender

</>复制代码

  1. public static void init() {
  2. //查找日志配置文件路径,没有则用log4j.xml
  3. String log4jPath = Play.configuration.getProperty("application.log.path", "/log4j.xml");
  4. URL log4jConf = Logger.class.getResource(log4jPath);
  5. boolean isXMLConfig = log4jPath.endsWith(".xml");
  6. //日志配置不存在,查找log4j.properties
  7. if (log4jConf == null) { // try again with the .properties
  8. isXMLConfig = false;
  9. log4jPath = Play.configuration.getProperty("application.log.path", "/log4j.properties");
  10. log4jConf = Logger.class.getResource(log4jPath);
  11. }
  12. //找不到配置文件就关闭日志
  13. if (log4jConf == null) {
  14. Properties shutUp = new Properties();
  15. shutUp.setProperty("log4j.rootLogger", "OFF");
  16. PropertyConfigurator.configure(shutUp);
  17. } else if (Logger.log4j == null) {
  18. //判断日志配置文件是否在应用目录下,加这条是因为play软件包目录下有默认的日志配置文件
  19. if (log4jConf.getFile().indexOf(Play.applicationPath.getAbsolutePath()) == 0) {
  20. // The log4j configuration file is located somewhere in the application folder,
  21. // so it"s probably a custom configuration file
  22. configuredManually = true;
  23. }
  24. //根据不同的类型解析
  25. if (isXMLConfig) {
  26. DOMConfigurator.configure(log4jConf);
  27. } else {
  28. PropertyConfigurator.configure(log4jConf);
  29. }
  30. Logger.log4j = org.apache.log4j.Logger.getLogger("play");
  31. // 测试模式下,将日志追加到test-result/application.log
  32. if (Play.runingInTestMode()) {
  33. org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger();
  34. try {
  35. if (!Play.getFile("test-result").exists()) {
  36. Play.getFile("test-result").mkdir();
  37. }
  38. Appender testLog = new FileAppender(new PatternLayout("%d{DATE} %-5p ~ %m%n"), Play.getFile("test-result/application.log").getAbsolutePath(), false);
  39. rootLogger.addAppender(testLog);
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }

初始化的代码可以看出log4j.xml的优先级高于log4j.properties,这里可以发现一个问题,Play的日志初始化完全是针对log4j来进行的,但是翻看Logger类的代码可以看到,所有的日志输出方法都会先判断是否使用java.util.logging.Logger来输出日志,在Logger类中也有一个forceJuli字段来判断是否使用,但是这个字段一直没有使用过,也就是说只要不手动改,那forceJuli一直是false。
如果没有做任何配置,那么直接使用Logger来输出日志,那么显示的类名就只会是Play,需要在配置文件中加入application.log.recordCaller=true来将日志输出时显示的类变为调用类名

查找文件路径

Play类中记录的路径有5种,分别为根目录路径,java文件路径,模板文件路径,主路由路径,模块路由路径。文件路径的添加很简单,就是将文件路径记录在对应的变量中,这里要提的一点是,conf文件夹是被加入到java文件路径中的,所以写在conf文件夹中的java源码也是可以使用的。当然,在conf文件夹里写源码大概会被骂死

加载模块

Play通过调用loadModules()来加载所有模块,使用的模块在3个地方查找,1是系统环境变量,环境变量MODULES记录的模块将加载,2是配置文件中记录的模块,配置信息为module.开头的模块被加载,3是应用目录下的modules文件夹下的模块被加载。在查找完毕后,会判断是否使用测试模式,是则加入_testrunner模块,并判断是否为dev模式,是则会加入_docviewer模块。
这里我们来看下Play将模块文件加入应用是如何做的

</>复制代码

  1. public static void addModule(String name, File path) {
  2. VirtualFile root = VirtualFile.open(path);
  3. modules.put(name, root);
  4. if (root.child("app").exists()) {
  5. javaPath.add(root.child("app"));
  6. }
  7. if (root.child("app/views").exists()) {
  8. templatesPath.add(root.child("app/views"));
  9. }
  10. if (root.child("conf/routes").exists()) {
  11. modulesRoutes.put(name, root.child("conf/routes"));
  12. }
  13. roots.add(root);
  14. if (!name.startsWith("_")) {
  15. Logger.info("Module %s is available (%s)", name, path.getAbsolutePath());
  16. }
  17. }

可以看出引入模块其实就是在各个路径下加入模块路径

加载插件

插件(plugins)是Play framework框架非常重要的组成部分,插件作用于Play运行时的方方面面,包括请求前后的处理,更新字节码等等,具体的插件使用说明我们放在之后的插件篇再说,这里就说说加载插件的过程。
插件的加载过程如下:

查找java文件路径下存在的play.plugins文件

读取每一个play.plugins,play.plugins中的记录由2部分组成,一个是插件优先级,一个是类名,逐行读取后根据优先级和类目组成LoadingPluginInfo,并加入List

根据优先级对List排序

根据排序完后的列表依次将插件加入至所有插件列表

初始化插件

更新插件列表

我们先来看看将插件加入所有插件列表的过程

</>复制代码

  1. protected boolean addPlugin( PlayPlugin plugin ){
  2. synchronized( lock ){
  3. //判断插件列表是否存在插件
  4. if( !allPlugins.contains(plugin) ){
  5. allPlugins.add( plugin );
  6. //根据优先级排序
  7. Collections.sort(allPlugins);
  8. //创建只读的插件列表
  9. allPlugins_readOnlyCopy = createReadonlyCopy( allPlugins);
  10. //启用插件
  11. enablePlugin(plugin);
  12. return true;
  13. }
  14. }
  15. return false;
  16. }

这是启用插件的方法

</>复制代码

  1. public boolean enablePlugin( PlayPlugin plugin ){
  2. synchronized( lock ){
  3. //检查是否存在插件
  4. if( allPlugins.contains( plugin )){
  5. //检查插件是否已在启动列表
  6. if( !enabledPlugins.contains( plugin )){
  7. //加入启动插件
  8. enabledPlugins.add( plugin );
  9. //排序
  10. Collections.sort( enabledPlugins);
  11. //创建只读列表
  12. enabledPlugins_readOnlyCopy = createReadonlyCopy( enabledPlugins);
  13. //更新插件列表
  14. updatePlayPluginsList();
  15. Logger.trace("Plugin " + plugin + " enabled");
  16. return true;
  17. }
  18. }
  19. }
  20. return false;
  21. }

这里有一个问题是,既然加入插件列表时会进行排序,那对List的排序是否就不需要了呢,其实不是的,因为在加入插件列表时会反射生成PlayPlugin的一个实例,如果实例的静态代码段对插件进行了修改,就会出现问题。
在插件加入完毕后,会循环列表进行插件的初始化

</>复制代码

  1. for( PlayPlugin plugin : getEnabledPlugins()){
  2. if( isEnabled(plugin)){
  3. initializePlugin(plugin);
  4. }
  5. }

这里为什么要在循环里再判断一遍插件是否启用呢,是为了让高优先级插件可以禁用低优先级插件。

预编译

预编译是为了在prod模式下加快加载速度,预编译方法的作用是将已经预编译好的文件读入或对文件进行预编译,对文件预编译包括了java文件的预编译以及模板文件的预编译,我们分别来看看

java预编译

在细说java预编译过程之前,我觉得有必要先来说一下play framework的类加载机制。
play.classloading.ApplicationClassloader是play框架的类加载器,所有play框架的代码均由ApplicationClassloader来加载。使用自建的类加载器主要是为了便于处理预编译后的字节码以及方便在dev模式下进行即时的热更新。
play.classloading.ApplicationClasses类是应用代码的容器,里面存放了所有的class。
ApplicationClassloader调用通过查找ApplicationClasses来获取对应的类代码(具体来说没有这么简单,因为这边只谈预编译,所以具体的流程暂且不谈,在之后的classloader篇再细说)
java预编译的入口在ApplicationClassloader.getAllClasses();它的过程如下:

检查插件是否有编译源码的方法,若有跳至4

扫描之前设定的javaPath下存在的java文件,读取类名,创建ApplicationClass,ApplicationClass类内有类名、java文件、java代码、编译后字节码、增强后字节码等字段,ApplicationClasses中存放的就是一个个ApplicationClass

使用eclipse JDT对源码进行编译,编译后的字节码存到对应的ApplicationClass中

遍历ApplicationClasses中的所有ApplicationClass,判断其是否需要增强,需要增强的类用插件进行增强并写入文件

play的编译器使用的是play.classloading.ApplicationCompiler类,这里对编译过程就不做更多的阐述。
这里有几点值得提一下

上面步骤2中扫描java文件只根据java文件名来判断类名,也就是说在步骤2的时候,ApplicationClasses容器中存放的class还只是单纯的外部类,而内部类与匿名内部类还不包括在内,在步骤3使用jdt编译时,ApplicationCompiler类会将匿名类与内部类都加到ApplicationClasses容器中,所以在第4步遍历的时候也会将内部类与匿名类的字节码文件增强然后加到文件中

由于步骤1会检查是否有插件会编译源码,也就意味着我们可以通过自写插件来覆盖play原有的编译过程。这点我觉得非常不错,因为在使用play做为工程框架时,等到代码量很大时,每次编译过程都会非常漫长,因为play默认会将所有java文件全部重新编译一遍,而这有时候是很不必要的,因为其实只要重新编译更改的文件即可,针对这一点我写了一个根据文件更改时间选择编译的插件,这个放到之后的play应用中再谈。

下面就是java预编译的主要代码

</>复制代码

  1. //判断是否有插件会进行编译
  2. if(!Play.pluginCollection.compileSources()) {
  3. List all = new ArrayList();
  4. //在javaPath中找所有类
  5. for (VirtualFile virtualFile : Play.javaPath) {
  6. all.addAll(getAllClasses(virtualFile));
  7. }
  8. List classNames = new ArrayList();
  9. //将所有类名组成list
  10. for (int i = 0; i < all.size(); i++) {
  11. ApplicationClass applicationClass = all.get(i);
  12. if (applicationClass != null && !applicationClass.compiled && applicationClass.isClass()) {
  13. classNames.add(all.get(i).name);
  14. }
  15. }
  16. //调用编译器编译
  17. Play.classes.compiler.compile(classNames.toArray(new String[classNames.size()]));
  18. }
  19. //遍历所有类,添加至allClasses,即ApplicationClasses容器中
  20. for (ApplicationClass applicationClass : Play.classes.all()) {
  21. //loadApplicationClass方法关键代码如下
  22. Class clazz = loadApplicationClass(applicationClass.name);
  23. if (clazz != null) {
  24. allClasses.add(clazz);
  25. }
  26. }

</>复制代码

  1. long start = System.currentTimeMillis();
  2. //从ApplicationClasses容器中找对应的ApplicationClass
  3. ApplicationClass applicationClass = Play.classes.getApplicationClass(name);
  4. if (applicationClass != null) {
  5. //isDefinable方法就是判断applicationClass是否已经编译且存在对应的javaClass
  6. if (applicationClass.isDefinable()) {
  7. return applicationClass.javaClass;
  8. }
  9. //查找之前是否存在编译结果
  10. byte[] bc = BytecodeCache.getBytecode(name, applicationClass.javaSource);
  11. if (Logger.isTraceEnabled()) {
  12. Logger.trace("Compiling code for %s", name);
  13. }
  14. //判断applicationClass是一个类还是package-info
  15. if (!applicationClass.isClass()) {
  16. definePackage(applicationClass.getPackage(), null, null, null, null, null, null, null);
  17. } else {
  18. loadPackage(name);
  19. }
  20. //如果之前的编译结果存在,就用之前的
  21. if (bc != null) {
  22. applicationClass.enhancedByteCode = bc;
  23. applicationClass.javaClass = defineClass(applicationClass.name, applicationClass.enhancedByteCode, 0, applicationClass.enhancedByteCode.length, protectionDomain);
  24. resolveClass(applicationClass.javaClass);
  25. if (!applicationClass.isClass()) {
  26. applicationClass.javaPackage = applicationClass.javaClass.getPackage();
  27. }
  28. if (Logger.isTraceEnabled()) {
  29. Logger.trace("%sms to load class %s from cache", System.currentTimeMillis() - start, name);
  30. }
  31. return applicationClass.javaClass;
  32. }
  33. //如果applicationClass编译过了或者编译后有字节码,进行字节码增强
  34. if (applicationClass.javaByteCode != null || applicationClass.compile() != null) {
  35. //进行字节码增强
  36. applicationClass.enhance();
  37. applicationClass.javaClass = defineClass(applicationClass.name, applicationClass.enhancedByteCode, 0, applicationClass.enhancedByteCode.length, protectionDomain);
  38. BytecodeCache.cacheBytecode(applicationClass.enhancedByteCode, name, applicationClass.javaSource);
  39. resolveClass(applicationClass.javaClass);
  40. if (!applicationClass.isClass()) {
  41. applicationClass.javaPackage = applicationClass.javaClass.getPackage();
  42. }
  43. if (Logger.isTraceEnabled()) {
  44. Logger.trace("%sms to load class %s", System.currentTimeMillis() - start, name);
  45. }
  46. return applicationClass.javaClass;
  47. }
  48. Play.classes.classes.remove(name);
  49. }
模板预编译

不同于java的预编译,模板的预编译结果虽然也会存放在precompile文件夹,但是在运行过程中模板并不是一次性全部加载的,模板的加载主要通过play.templates.TemplateLoader来进行,TemplateLoader中存放了使用过的模板信息。
在模板预编译过程中,主要是步骤如下:

扫描Play.templatesPath目录下所有模板文件

遍历文件,用TemplateLoader.load来加载源文件,并进行模板编译,产生Groovy源码

对编译后的Groovy源码进行编译,并用base64加密写入文件

这里只对模板预编译流程做一个梳理,至于编译的过程放在之后的模板篇再说

play framework的启动

从上一篇server与servletWrapper中我们可以发现,play framework并不是一定在脚本启动之后便启动服务器,在我们使用dev模式进行开发时也会发现,play总是需要接受到一个请求后才会有真正的启动流程。我们这一节就来看看play的启动过程是怎么样的,这个启动与server或servletWrapper的启动的区别在于,play启动后便真正开始业务处理,而server与servletWrapper的启动仅仅是启动了监听端口,当然要清楚的是servletWrapper启动时也会自动启动play

</>复制代码

  1. public static synchronized void start() {
  2. try {
  3. //如果已经启动了,先停止,这里是为了dev模式的热更新
  4. if (started) {
  5. stop();
  6. }
  7. //如果不是独立的server,即如果不是放在servlet容器中运行,注册关闭事件
  8. if( standalonePlayServer) {
  9. // Can only register shutdown-hook if running as standalone server
  10. if (!shutdownHookEnabled) {
  11. //registers shutdown hook - Now there"s a good chance that we can notify
  12. //our plugins that we"re going down when some calls ctrl+c or just kills our process..
  13. shutdownHookEnabled = true;
  14. Runtime.getRuntime().addShutdownHook(new Thread() {
  15. public void run() {
  16. Play.stop();
  17. }
  18. });
  19. }
  20. }
  21. //如果是dev模式启动,重新加载所有class和插件
  22. if (mode == Mode.DEV) {
  23. // Need a new classloader
  24. classloader = new ApplicationClassloader();
  25. // Put it in the current context for any code that relies on having it there
  26. Thread.currentThread().setContextClassLoader(classloader);
  27. // Reload plugins
  28. pluginCollection.reloadApplicationPlugins();
  29. }
  30. // 读取配置文件
  31. readConfiguration();
  32. // 配置日志
  33. String logLevel = configuration.getProperty("application.log", "INFO");
  34. //only override log-level if Logger was not configured manually
  35. if( !Logger.configuredManually) {
  36. Logger.setUp(logLevel);
  37. }
  38. Logger.recordCaller = Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));
  39. // 设置语言
  40. langs = new ArrayList(Arrays.asList(configuration.getProperty("application.langs", "").split(",")));
  41. if (langs.size() == 1 && langs.get(0).trim().length() == 0) {
  42. langs = new ArrayList(16);
  43. }
  44. // 重新加载模板
  45. TemplateLoader.cleanCompiledCache();
  46. // 设置secretKey
  47. secretKey = configuration.getProperty("application.secret", "").trim();
  48. if (secretKey.length() == 0) {
  49. Logger.warn("No secret key defined. Sessions will not be encrypted");
  50. }
  51. // 设置默认web encoding
  52. String _defaultWebEncoding = configuration.getProperty("application.web_encoding");
  53. if( _defaultWebEncoding != null ) {
  54. Logger.info("Using custom default web encoding: " + _defaultWebEncoding);
  55. defaultWebEncoding = _defaultWebEncoding;
  56. // Must update current response also, since the request/response triggering
  57. // this configuration-loading in dev-mode have already been
  58. // set up with the previous encoding
  59. if( Http.Response.current() != null ) {
  60. Http.Response.current().encoding = _defaultWebEncoding;
  61. }
  62. }
  63. // 加载所有class
  64. Play.classloader.getAllClasses();
  65. // 加载路由
  66. Router.detectChanges(ctxPath);
  67. // 初始化缓存
  68. Cache.init();
  69. // 运行插件onApplicationStart方法
  70. try {
  71. pluginCollection.onApplicationStart();
  72. } catch (Exception e) {
  73. if (Play.mode.isProd()) {
  74. Logger.error(e, "Can"t start in PROD mode with errors");
  75. }
  76. if (e instanceof RuntimeException) {
  77. throw (RuntimeException) e;
  78. }
  79. throw new UnexpectedException(e);
  80. }
  81. if (firstStart) {
  82. Logger.info("Application "%s" is now started !", configuration.getProperty("application.name", ""));
  83. firstStart = false;
  84. }
  85. // We made it
  86. started = true;
  87. startedAt = System.currentTimeMillis();
  88. // 运行插件afterApplicationStart方法
  89. pluginCollection.afterApplicationStart();
  90. } catch (PlayException e) {
  91. started = false;
  92. try { Cache.stop(); } catch (Exception ignored) {}
  93. throw e;
  94. } catch (Exception e) {
  95. started = false;
  96. try { Cache.stop(); } catch (Exception ignored) {}
  97. throw new UnexpectedException(e);
  98. }
  99. }

可以看出play的启动和play的初始化有很多相同的地方,包括加载配置,加载日志等,启动过程有很多有意思的地方

play的启动不会重置模块列表,也就是说如果在dev模式下对配置文件进行修改增加了模块必须要重启服务器,热更新是无效的。

在play的初始化过程中,如果是使用容器打开服务器时就会加载预编译文件,这时候已经读取一遍预编译源码了,所有在启动过程中的getAllClasses就不会再去查找了

插件的onApplicationStart方法一般就是执行些插件初始化的工作,所以遇到错误就会中断启动过程,而afterApplicationStart是在启动完成后在运行的,很有意思的是,用@OnApplicationStart标识的job类是在afterApplicationStart阶段运行的,而不是onApplicationStart阶段。那为什么要叫这个名字

可以看出路由的解析是在play的启动过程中进行的,具体过程就是读取路径下的路由文件,然后路由的具体解析过程放在模板篇一起讲吧

总结

Play类的初始化与启动已经说的差不多了,下一篇我们来看下ActionInvoker与mvc

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70955.html

相关文章

  • Play framework源码解析 Part1:Play framework 介绍、项目构成及启动

    摘要:注本系列文章所用版本为介绍是个轻量级的框架,致力于让程序员实现快速高效开发,它具有以下几个方面的优势热加载。在调试模式下,所有修改会及时生效。抛弃配置文件。约定大于配置。 注:本系列文章所用play版本为1.2.6 介绍 Play framework是个轻量级的RESTful框架,致力于让java程序员实现快速高效开发,它具有以下几个方面的优势: 热加载。在调试模式下,所有修改会及时...

    Riddler 评论0 收藏0
  • Play framework源码解析 Part2:ServerServletWrapper

    摘要:是一个抽象类,继承了接口,它的方法是这个类的核心。因为可能需要一个返回值,所以它同时继承了接口来提供返回值。 注:本系列文章所用play版本为1.2.6 在上一篇中我们剖析了Play framework的启动原理,很容易就能发现Play framework的启动主入口在play.server.Server中,在本节,我们来一起看看Server类中主要发生了什么。 Server类 既然是...

    JiaXinYi 评论0 收藏0
  • 如何使用 Docker 部署一个基于 Play Framework Scala Web 应用?

    摘要:本文将着重介绍使用来部署一个基于的应用程序会多么便捷,当然这个过程主要基于插件。如你所见,这是一个基于的应用程序。这个基于的应用程序将无法被访问。总结可以如此简单地给一个基于的应用程序建立,相信很多人都会像笔者一样离不开它。 本文作者 Jacek Laskowski 拥有近20年的应用程序开发经验,现 CodiLime 的软件开发团队 Leader,曾从 IBM 取得多种资格认证。在这...

    2501207950 评论0 收藏0
  • Play Framework升级到2.6.x填坑记录

    摘要:为了使用最新的,升级到配置修改根据官网的升级指南,修改文件,更改插件版本号文件中,把和单独加入。此文件为首页的模板。推测可能是版本和版本的首页模板不同,于是到官网下载版本的,找到并覆盖项目的相应文件。添加插件的语句至此,升级成功完成。 为了使用最新的Play WS Api,升级到play 2.6.21 1.配置修改 根据官网的升级指南,修改plugins.sbt文件,更改插件版本号:a...

    voidking 评论0 收藏0

发表评论

0条评论

xuxueli

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<