Java implements dual daemon and Linux daemon for linux server programs
I. Introduction
Many of the current server-side programs are developed based on Java. For Socket programs developed for Java, You need to manually restart the server after the server goes online, it is still very troublesome.
Most of the solutions are to use other processes to daemon the server program. If the server program fails, the daemon process is used to start the server program.
What if the daemon fails? Use dual-daemon to improve stability. Daemon A is responsible for monitoring server programs and daemon B. Daemon B is responsible for monitoring and daemon A. If any party has problems, it can quickly start the program, improve the stability of the server program.
The Java Runtime Environment is different from programs developed in C and other languages. Java programs run on JVM. Unlike the C language, you can directly create a process. Creating a process in Java is equivalent to starting a program using java-jar xxx. jar.
The Java Startup Program does not have A single instance limitation similar to C #. You can start multiple programs, but you cannot start multiple programs. You cannot have multiple daemon A to daemon the server program, what if I start multiple server programs?
Ii. technical explanation
Here the technical explanation is relatively rough. Please refer to Baidu for details. Here we will only explain the function.
1. jps command.
The command tool that comes with JDK. You can use jps-l to list running Java programs and display the pid and Name of the Java program. It is only valid for Java programs. In fact, the JVM running
2. Use of the java. nio. channels. FileLock class
This is a class in Java new IO. It can be used to maintain the lock on the file to be read, and to determine whether the file is used by other programs when there is a lock in the file.
3. ProcessBuilder and Process
These two principles are similar. They all call the system command to run and then return information. However, hard coding will lead to the loss of portability of your Java program. You can separate the commands into the configuration file.
Iii. Design Principles
Server: Server program
A: Daemon
B: Daemon B
A. lock: file lock of daemon
B. lock: file lock of daemon B
----------------------------------------------------------------------------------
Step 1: first, consider the Server, only the guard between A and B
1. A checks whether B is alive and starts B if no
2. B checks whether A is alive and starts A if no
3. During the running process, A and B get each other's filelock. If they get the filelock and prove that the opposite side is down, start the other side.
4. A obtains. lock file lock. If the lock proves that A is not started, A runs. If the lock is not obtained, it indicates that A is started, or B gets the lock when judging, if A has been started and A does not need to be started again, B will start A again if the lock is obtained when B determines that it is not locked.
5. The principle of B startup is the same as that of.
6. If A crashes during running and B determines that A is down, it starts. B.
Step 2: Join the Server
1. A is used to protect B and Server, and B is used to protect.
2. The principle is the same as Step 1. Only A has multiple tasks that guard the Serer.
3. When A is running, use the process pid to detect that the Server is down and start the Server.
4. If both Server and A are down, B will start A and A will start the Server.
5. If Server and B are down, A starts Server and B
6. If both A and B are suspended, the daemon will end.
Step 3: Use Shutdown to end the daemon. Otherwise, it will be automatically started after the Server is stopped.
IV. Implementation
1. Implementation of GuardA
1 public class GuardA {2 // GuardA is used to maintain its own lock 3 private File fileGuardA; 4 private FileOutputStream fileOutputStreamGuardA; 5 private FileChannel fileChannelGuardA; 6 private FileLock fileLockGuardA; 7 // GuardB is used to detect the lock 8 private File fileGuardB of B; 9 private FileOutputStream fileOutputStreamGuardB; 10 private FileChannel fileChannelGuardB; 11 private FileLock fileLockGuardB; 12 13 public GuardA () throws Ex Ception {14 fileGuardA = new File (Configure. GUARD_A_LOCK); 15 if (! FileGuardA. exists () {16 fileGuardA. createNewFile (); 17} 18 // get the filelock. If no GuardA is enabled, Exit 19 fileOutputStreamGuardA = new FileOutputStream (fileGuardA); 20 fileChannelGuardA = fileOutputStreamGuardA. getChannel (); 21 fileLockGuardA = fileChannelGuardA. tryLock (); 22 if (fileLockGuardA = null) {23 System. exit (0); 24} 25 26 fileGuardB = new File (Configure. GUARD_ B _LOCK); 27 if (! FileGuardB. exists () {28 fileGuardB. createNewFile (); 29} 30 fileOutputStreamGuardB = new FileOutputStream (fileGuardB); 31 fileChannelGuardB = fileOutputStreamGuardB. getChannel (); 32} 33 34/** 35 * check whether B exists 36*37 * @ return true B already exists 38 */39 public boolean checkGuardB () {40 try {41 fileLockGuardB = fileChannelGuardB. tryLock (); 42 if (fileLockGuardB = null) {43 return true; 44} else {45 fileLockGuardB. release (); 46 return false; 47} 48} catch (IOException e) {49 System. exit (0); 50 // never touch51 return true; 52} 53} 54}
2. Implementation of GuardServer
1 public class GuardServer {2 private String servername; 3 4 public GuardServer (String servername) {5 this. servername = servername; 6} 7 8 public void startServer (String cmd) throws Exception {9 System. out. println ("Start Server:" + cmd); 10 // separate commands 11 // String [] cmds = cmd. split (""); 12 // ProcessBuilder builder = new ProcessBuilder (cmds); 13 14 // 15 ProcessBuilder builder = new ProcessBuilder (ne W String [] {"/bin/sh", "-c", cmd}); 16 // locate the output of the server program to/dev/tty17 builder. redirectOutput (new File ("/dev/tty"); 18 builder. redirectError (new File ("/dev/tty"); 19 builder. start (); // throws IOException20 Thread. sleep (10000 ); 21} 22 23/** 24 * check whether the service exists 25*26 * @ return the pid27 * @ return pid of the configured java program. 0 returns the pid <= 0 indicating that the specified java program does not run 28 ***/29 public int checkServer () throws Exception {30 int pid =-1; 31 Proces S process = null; 32 BufferedReader reader = null; 33 process = runtime.getruntime(.exe c ("jps-l"); 34 reader = new BufferedReader (new InputStreamReader (process. getInputStream (); 35 String line; 36 while (line = reader. readLine ())! = Null) {37 String [] strings = line. split ("\ s {1,}"); 38 if (strings. length <2) 39 continue; 40 if (strings [1]. contains (servername) {41 pid = Integer. parseInt (strings [0]); 42 break; 43} 44} 45 reader. close (); 46 process. destroy (); 47 return pid; 48} 49}
3. Implementation of GuardAMain
1 public class GuardAMain {2 public static void main (String [] args) throws Exception {3 GuardA guardA = new GuardA (); 4 Configure configure = new Configure (); 5 GuardServer server = new GuardServer (configure. getServername (); 6 while (true) {7 // if GuardB is not running run GuardB 8 if (! GuardA. checkGuardB () {9 System. out. println ("Start GuardB ..... "); 10 runtime.getruntime(cmd.exe c (configure. getStartguardb (); 11} 12 // detect server survival 13 if (server. checkServer () <= 0) {14 boolean isServerDown = true; 15 // trip check16 for (int I = 0; I <3; I ++) {17 // if the service is alive 18 if (server. checkServer ()> 0) {19 isServerDown = false; 20 break; 21} 22} 23 if (isServerDown) 24 server. startServer (configure. getStartserver (); 25} 26 Thread. sleep (configure. getInterval (); 27} 28} 29}
4. Shutdown implementation
1 public class ShutDown { 2 public static void main(String[] args) throws Exception { 3 Configure configure = new Configure(); 4 System.out.println("Shutdown Guards.."); 5 for (int i = 0; i < 3; i++) { 6 Process p = Runtime.getRuntime().exec("jps -l"); 7 BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); 8 String line; 9 while ((line = reader.readLine()) != null) {10 if (line.toLowerCase().contains("Guard".toLowerCase())) {11 String[] strings = line.split("\\s{1,}");12 int pid = Integer.parseInt(strings[0]);13 Runtime.getRuntime().exec(configure.getKillcmd() + " " + pid);14 }15 }16 p.waitFor();17 reader.close();18 p.destroy();19 Thread.sleep(2000);20 }21 System.out.println("Guards is shutdown");22 }23 }
5. GuardB is similar to GuardA
5. download and use
Project Folder: guard_demo
: Http://pan.baidu.com/s/1bn1Y6BX
If you have any questions or suggestions, contact me
How does one implement java daemon programming in linux?
A program is a process.
What else do you want?
Package the executable program into a jar package, and then execute jave-jar yourApplicationName. jar under the corresponding user.
How does one implement the daemon in Java?
In Windows, the system serves the same program. after checking the information for a long time, I did not find any way to develop the linux daemon in java. the implementation code is published as follows: import java. io. bufferedWriter; import java. io. file; import java. io. fileWriter;
For more information, see:
Java.e800.com.cn/...1.html