問題:在做項目時,遇到jar版本沖突的問題,並且老代碼依賴不能用新jar包代替,要保證功能不變須要保證兩個jar都能使用
思路:使用runtime 的exec 方式另啟線程運行,然后返回結果
解決:
1):創建可運行的jar包,並創建入口main方法,方法實現新功能的調用與結果或異常的返回
public static void main(String[] args) { try { //接收參數 String privateKeyPath = args [0]; /* 業務邏輯 */ System.out.println("ok" ); System.out.println(業務邏輯有返回結果,如果有 ); } catch (Exception e ) { System.out.println("error" ); System.out.println(e); }
2):在項目新創建調用方法,本例使用windows 環境
Runtime r = Runtime.getRuntime(); try{ //new String[]{"/bin/sh","-c","ln -s exe1 exe2"}) linux下的命令 Process proc = r .exec(new String[]{"cmd" ,"/c" ,"java -jar citicbankclient.jar gbz"}); BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gbk" )); String line = null ; while ((line = reader.readLine()) != null){ //接收system.out輸出 System. out.println(line); } int exitVal = proc.waitFor(); //調用是否成功 System. out.println(exitVal == 0 ? "ok" : "error" ); } catch(Exception e ){ e.printStackTrace(); }
注意:這種方式是把新功能另啟jvm來完成jar包隔離的,在高並發情況下會啟動多個jvm,如果jvm不能很快的執行完,會消耗大量內存及cpu資源,
解決這個問題只能控制並發量