前段時間,產品提了個挺離譜的需求:經過java服務啓動本身所須要的數據庫和redis。什麼意思呢,意思就是咱們須要提供一個java服務,可是呢,咱們這個java服務用到的mysql和redis沒有現成的,須要由這個java服務去安裝部署mysql和redis,而後再提供給本身用。
emmmm…當時我人就傻了,後面我一想,產品都敢想這個需求,難到我堂堂一個技術還不敢去實現嗎?java
收起咱們40米大砍刀,直接上乾貨:mysql
public static String doExec(String instruction) { logger.log(Level.INFO, "===execute instruction :" + instruction); StringBuffer result = new StringBuffer(); Process process = null; BufferedReader bufrIn = null; BufferedReader bufrError = null; try { Runtime run = Runtime.getRuntime(); process = run.exec(instruction); // 方法阻塞, 等待命令執行完成(成功會返回0) process.waitFor(); bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8")); // 讀取輸出 String line; while ((line = bufrIn.readLine()) != null) { result.append(line).append('\n'); } while ((line = bufrError.readLine()) != null) { result.append(line).append('\n'); } logger.log(Level.INFO, "===execute instruction success :" + instruction+" , result is :"+result); } catch (Exception e) { logger.log(Level.WARNING, "===execute instruction error :" + e); } finally { MyFileUtils.closeStream(bufrIn); MyFileUtils.closeStream(bufrError); // 銷燬子進程 if (process != null) { process.destroy(); } } return result.toString(); }
固然,這個方法不僅僅侷限於安裝部署mysql和redis,支持任意sh命令,感興趣的朋友能夠拿去試試了!git
>>>源碼下載連接>>>redis