Implementation principle of Java Server hot deployment, java deployment

Source: Internet
Author: User

Implementation principle of Java Server hot deployment, java deployment

Today, I found a note written in the elephant's note in my early years, which was previously placed on ijavaby. Now it cannot be accessed. Another colleague was discussing this issue a few days ago. Here we will share with you.


During web application development or game server development, we are always using hot deployment. The purpose of hot deployment is to save time for application development and release. For example, we often enable hot deployment when using Tomcat, Jboss, and other application servers to develop applications. Hot deployment: Simply put, we replace the packaged application directly with the original application without shutting down or restarting the server. Everything is so simple. How is hot deployment implemented? In this article, I will write an instance, which is a container application that allows users to publish their own applications and supports hot deployment.


To implement hot deployment in Java, you must first understand the Loading Method of classes in Java. Classes of each application are loaded by ClassLoader. Therefore, to implement an application that supports hot deployment, we can use a separate ClassLoader to load each user-defined application. Then, when a user-defined application changes, we first destroy the original application and then use a new ClassLoader to load the changed application. All other applications will not be disturbed. Let's take a look at the design of the application:


With the overall implementation, we can think of the following goals:
1. Define a user-defined application interface. This is because we need to load the User-Defined application in the container application. 2. We also need a configuration file for users to configure their applications. 3. When the application is started, all existing user-defined applications are loaded. 4. To support hot deployment, we need a listener to listen for changes to each file in the application release directory. In this way, after an application is re-deployed, we can get a notification for hot deployment.
Implementation:
First, we define an interface. Each user-defined program must contain a unique class that implements this interface. The Code is as follows:
public interface IApplication {        public void init();               public void execute();               public void destory();       }


In this example, each user-defined application must first be packaged into a jar file and then published to a specified directory in the specified format, at the first release, you also need to add the application configuration to the configuration file. Therefore, first, we need to define a class that can load the jar file in the specified directory:
        public ClassLoader createClassLoader(ClassLoader parentClassLoader, String... folders) {              List<URL> jarsToLoad = new ArrayList<URL>();               for (String folder : folders) {                     List<String> jarPaths = scanJarFiles(folder);                      for (String jar : jarPaths) {                            try {                                  File file = new File(jar);                                  jarsToLoad.add(file.toURI().toURL());                           } catch (MalformedURLException e) {                                  e.printStackTrace();                           }                     }              }              URL[] urls = new URL[jarsToLoad.size()];              jarsToLoad.toArray(urls);               return new URLClassLoader(urls, parentClassLoader);       }



This method is simple, that is, scanning the jar file from multiple directories and returning a new URLClassLoader instance. As for the scanJarFiles method, you can download the source code of this article. Then, we need to define a configuration file. users need to configure their custom application information here. In this way, the container application then loads all applications based on the configuration file:
<apps>        <app>               <name> TestApplication1</name >               <file> com.ijavaboy.app.TestApplication1</file >        </app>        <app>               <name> TestApplication2</name >               <file> com.ijavaboy.app.TestApplication2</file >        </app></apps>


This configuration is in XML format. Each app tag represents an application. For each application, you need to configure the name and the complete path and name of the class that implements the IApplication interface. With this configuration file, we need to parse it. In this example, xstream is used, which is very simple. You can download the source code and see it. This is skipped. The name of each application is crucial, because in this example, our release directory is the application directory under the entire project release directory, this is the directory where all user-defined applications are released. To publish an application, you must first create a folder with the same name as the name configured here in the directory, and then publish the packaged application to the folder. (You must do this; otherwise, the release will fail in this example ). Now, the method and configuration for loading jar are available. The following is the core part of the example. Right, it is the application management class, this class is used to manage and maintain each user-defined application. The first thing to do is load an application:
        public void createApplication(String basePath, AppConfig config){              String folderName = basePath + GlobalSetting. JAR_FOLDER + config.getName();              ClassLoader loader = this.jarLoader .createClassLoader(ApplicationManager. class.getClassLoader(), folderName);                             try {                     Class<?> appClass = loader. loadClass(config.getFile());                                          IApplication app = (IApplication)appClass.newInstance();                                          app.init();                                           this.apps .put(config.getName(), app);                                   } catch (ClassNotFoundException e) {                     e.printStackTrace();              } catch (InstantiationException e) {                     e.printStackTrace();              } catch (IllegalAccessException e) {                     e.printStackTrace();              }       }


We can see that this method receives two parameters: the basic path and the application configuration. The basic path is actually the address of the Project release directory, while AppConfig is actually an entity ing of app tags in the configuration file. This method loads the specified class from the specified configuration directory, then, call the init method of the application to initialize the custom application. Finally, the loaded application is put into the memory. Now, all the preparations have been completed. Next, when the entire application starts, we need to load all user-defined applications. Therefore, we add a method in ApplicationManager:
        public void loadAllApplications(String basePath){                             for(AppConfig config : this.configManager.getConfigs()){                      this.createApplication(basePath, config);              }       }


This method loads all applications configured by the user to the container application. Now, do we need to write two independent applications to test the effect? To write this application, first create a java application and then reference this example project, or package the project in this example into a jar file and reference it to this independent application, because this independent application must contain a class that implements the IApplication interface. Let's take a look at the example of an independent application:
public class TestApplication1 implements IApplication{        @Override        public void init() {              System. out.println("TestApplication1-->init" );       }        @Override        public void execute() {              System. out.println("TestApplication1-->do something" );       }        @Override        public void destory() {              System. out.println("TestApplication1-->destoryed" );       }}



Is it easy? Yes, it's that simple. You can write another independent application. Next, you also need to configure in applications. xml. It is very simple to add the following code to the apps Tag:
        <app>               <name> TestApplication1</name >               <file> com.ijavaboy.app.TestApplication1</file >        </app>


Next, we will go to the core part of this article. Next, all our tasks will be concentrated on hot deployment. In fact, you may still think hot deployment is mysterious,, I believe you will not think that in a minute. To implement hot deployment, we have said that a listener is required to listen to applications in the publishing directory. In this way, when the jar file of an application changes, we can perform hot deployment. In fact, there are many ways to monitor directory file changes. In this example, I use a common-vfs open-source Virtual File System of apache. If you are interested, visit http://commons.apache.org/proper/commons-vfs /. Here, we inherit its FileListener interface and implement fileChanged:
        public void fileChanged (FileChangeEvent event) throws Exception {              String ext = event.getFile().getName().getExtension();               if(!"jar" .equalsIgnoreCase(ext)){                      return;              }                            String name = event.getFile().getName().getParent().getBaseName();                            ApplicationManager. getInstance().reloadApplication(name);                     }


When a file changes, this method is called back. Therefore, the reloadApplication method of ApplicationManager is called in this method to reproduce and load the application.
        public void reloadApplication (String name){              IApplication oldApp = this.apps .remove(name);                             if(oldApp == null){                      return;              }                            oldApp.destory();     //call the destroy method in the user's application                            AppConfig config = this.configManager .getConfig(name);               if(config == null){                      return;              }                            createApplication(getBasePath(), config);       }


When recreating an application, we first Delete the application from the memory, call the destory method of the original application, and recreate the application instance according to the configuration. So far, do you still think hot deployment is very mysterious and profound? Everything is so simple. Now let's get down to the point. To make our custom listening interface work effectively, we also need to specify the directory to be listened:
        public void initMonitorForChange(String basePath){               try {                      this.fileManager = VFS.getManager();                                          File file = new File(basePath + GlobalSetting.JAR_FOLDER);                     FileObject monitoredDir = this.fileManager .resolveFile(file.getAbsolutePath());                     FileListener fileMonitorListener = new JarFileChangeListener();                      this.fileMonitor = new DefaultFileMonitor(fileMonitorListener);                      this.fileMonitor .setRecursive(true);                      this.fileMonitor .addFile(monitoredDir);                      this.fileMonitor .start();                     System. out.println("Now to listen " + monitoredDir.getName().getPath());                                   } catch (FileSystemException e) {                     e.printStackTrace();              }       }


Here, the listener is initialized. We use VFS DefaultFileMonitor to complete the listener. The monitored directory is the application publishing directory applications. Next, we modify the startup method to ensure that the entire application can run continuously without stopping:
        public static void main(String[] args){                            Thread t = new Thread(new Runnable() {                                           @Override                      public void run() {                           ApplicationManager manager = ApplicationManager.getInstance();                           manager.init();                     }              });                            t.start();                             while(true ){                      try {                           Thread. sleep(300);                     } catch (InterruptedException e) {                           e.printStackTrace();                     }              }       }


Now, everything is over. Now you know exactly what hot deployment is like, right? Do not understand? OK. Let's take a look at the source code!
I have already installed the source code on GitHub. Address: Ghost.
Finally, if there is something wrong with this article, please correct me. Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.