java操作shell命令(4)—监控一个服务是否正常运行,如果停机,则启动!
package park.mecdaemons.bussiness; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; /** * 监控进程 * @Author Miracle Luna * @Date 2020/9/10 15:22 * @Version 1.0 * @description 监控进程状态 */ @Component @Slf4j public class MonitorService { private int count = 0; /** * @Author Smith * @Description 设置每隔3分钟执行一次 * @Date 15:23 2020/9/10 * @Param * @return void **/ @Scheduled(cron = "0 */3 * * * ?") private void process() throws Exception { log.info("this is scheduler task running " + new SimpleDateFormat("yyyy-MM-dd HH:mm:s").format(new Date()) +(count++)); String [] getRunningcmd = {"/bin/sh","-c","service mec-sys-service status"}; String result = execShellCommand(getRunningcmd, null); log.info("执行命令返回结果:"+result); //监测进程消失时,启动进程 if(!result.contains("Running")){ String[] cmds = {"/bin/sh","-c","service mec-sys-service start"}; ServiceUtils.execCmd(cmds); }else{ //记录一下日志 log.info("正常运行="+new SimpleDateFormat("yyyy-MM-dd HH:mm:s").format(new Date())); } System.out.println(result); } /** * 执行系统命令, 返回执行结果 * @param cmd 需要执行的命令 * @param dir 执行命令的子进程的工作目录, null 表示和当前主进程工作目录相同 */ public static String execShellCommand(String[] cmd, File dir) throws Exception { StringBuilder result = new StringBuilder(); Process process = null; BufferedReader bufrIn = null; BufferedReader bufrError = null; try { // 执行命令, 返回一个子进程对象(命令在子进程中执行) process = Runtime.getRuntime().exec(cmd, null, dir); // 方法阻塞, 等待命令执行完成(成功会返回0) process.waitFor(); // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出(PS: 子进程的输出就是主进程的输入) bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8")); // 读取输出 String line = null; while ((line = bufrIn.readLine()) != null) { result.append(line).append('\n'); } while ((line = bufrError.readLine()) != null) { result.append(line).append('\n'); } } finally { closeStream(bufrIn); closeStream(bufrError); // 销毁子进程 if (process != null) { process.destroy(); } } // 返回执行结果 return result.toString(); } private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (Exception e) { log.error("关闭流时出现异常="+e.getMessage()); } } } public static void main(String[] args) { //Not running Running [17507] String str="Not running"; if(str.contains("Running")){ System.out.println("包含=="+str); }else{ System.out.println("不包含=="+str); } } }
版权声明:本文为zlxdream815原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。