Java: How do I get the program to restart on demand?

Source: Internet
Author: User

Text before the beginning of the nonsense: The program here includes b/S Web application, also includes the standalone class C/S Java application. Why do you want to restart yourself? Scenario 1:Distributed environment, there will be many applications (that is, including C/S Java application, and b/S Web application) deployed in different environments, in order to manage the convenience, usually put some common configuration, such as: alarm email email account/password/ SMTP information, common FTP account information, even JDBC connection string information, etc., unified in a location (shared network storage directory, Redis cache, database, zookeeper, remote service can be), this is easier to manage. Like e-mail account This information is OK, each application subscription configuration changes, when found to change, if it is the spring environment, directly call Applicationcontext.refresh (), the configuration will be re-refreshed. But for the data source this special configuration, it is more difficult to get, to consider the connection pool has been successfully connected to the Connection object, has been found through the old datasource data, with the old datasource associated Sqlsesstionfactory, Mapper instances and so on, to all the exchange, it is difficult to ensure that the best way is to let the program restart. Scenario 2:Write the program, there are hidden bugs unavoidable, Absolute 0 bug program is still very rare, if with the program running time increasing, program performance is getting worse or suspended animation, need to restart, usually need to remotely hit Linux, Knock command kill process, and then restart Java Application, this for unfamiliar with Linux novice manager, one may be more unfamiliar, and not necessarily have executive authority, so through a friendly monitoring management interface, click the Restart button, let the designated program restart, it will be easier to accept. Body start: First, how does the program know that it needs to be restarted? Obviously, if there is a program, the user wants to shut down normally, the program restarts automatically, so the loop, which is not shut down the malicious program. Therefore, the program should be monitored by a separate process and receive specific instructions, without affecting the user's normal shutdown program, thinking: When the program starts, generate a unique UUID (or other identity, as long as the global unique is guaranteed), and then register a temporary node to zookeeper. For example:/app/uuid-1 Such a monitoring center, as long as the scan/app under the number of temporary nodes, you know which applications are currently running. When an administrator wants to restart an app from the Monitoring center, it can write to zookeeper the contents of a node/command/uuid-1 node, which is: Restart the application starts, listens to the/COMMAND/UUID-1 node's data changes,  Once the data content of the restart is found, it is thought to have received the restart instruction, and then, according to the following treatment, self-destruction, re-reincarnation. Second, Java application Sample code to restart the Web:
12345678910111213 Runtime.getRuntime().addShutdownHook(newThread() {    publicvoidrun() {        try{            String restartCmd = "nohup java -jar xxx.jar";            Thread.sleep(10000);//等10秒,保证分身启动完成后,再关掉自己            logger.debug("程序重启完成!");        catch(Exception e) {            logger.error("重启失败,原因:", e);        }    }});logger.debug("程序准备重启!");System.exit(0);
Can improve the place: a) sleep (10000) that is waiting for 10 seconds, and so their "fen" after the start of the good, then the "flesh" to kill. Here the 10 seconds, in fact, is also a pat head, if the pursuit of perfection, in theory, as long as the system in the process of the emergence of a new start of "Fen", you can be "real" humane destruction. Questions:What if you know that "fen" has started to complete? Answer:Java can get the output of jps-l, know all the current Java processes, so that you can know that the specified application has not started. You can get the output of jps-l once before restarting, reboot, then perform the output of jps-l once, compare two times output, if find out a new named process name, it means "fen" start to complete, you can end yourself. Attached: Java code get JPS output
123456789101112131415161718192021222324252627282930 importorg.apache.logging.log4j.*;importjava.io.BufferedReader;importjava.io.InputStreamReader;publicfinalclassRuntimeUtil {     privatestaticLogger logger = LogManager.getLogger();    publicstaticString exec(String command) {        StringBuilder sb = newStringBuilder();        try{            Process process = Runtime.getRuntime().exec(command);            BufferedReader reader = newBufferedReader(newInputStreamReader(process.getInputStream()));            String line = null;            while((line = reader.readLine()) != null) {                sb.append(line);            }            process.getOutputStream().close();            reader.close();            process.destroy();        catch(Exception e) {            logger.error("执行外部命令错误,命令行:"+ command, e);        }        returnsb.toString();    }    publicstaticString jps() {        returnexec("jps -l");    }}

  

b) Java-jar Xxx.jar Here is also not very good, one is Xxx.jar is a string, compile time can not find errors, the second is the path is the relative path, even if the start is successful, the final JPS show the process name is a jar, see what the actual corresponding program (details can refer to the settings Java-jar Process display name), you can code to get the actual path of the current program
1234567 publicstaticString getJarExecPath(Class clazz) {    String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();    if(OSUtil.getOSname().equals(OSType.Windows)) {        returnpath.substring(1);    }    return path;}

Osutil code gets from here

  

Third, the Web application restart here only to discuss the solution deployed on JBoss, JBoss CLI command-line interface learning (for JBoss EAP 6.2+) JBoss eap:native Management API Learning in these two articles, has given the method of using code or shell command to control JBoss, so the Web application on-demand restart idea is: From the monitoring interface Click "Restart" a Web application, the background code first the Web application Disable off, and then re-enable or assign

Java: How do I get the program to restart on demand?

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.