XXL-JOB使用命令行的方式啟動python時,日志過多導致阻塞的解決方式


一、Runtime.getRuntime().exec()的阻塞問題

這個問題也不能算是XXL-JOB的問題,而是Java的Runtime.getRuntime().exec()造成的,BufferedReader的緩沖區大小有限,當不能及時從緩沖區中把輸出取走,那么緩沖區滿了之后就會導致程序阻塞;

1、如何解決

最簡單的方式就是將正常輸出和異常輸出使用兩個不同的線程進行操作


Process process = Runtime.getRuntime().exec(command);
StreamOutter errorGobbler = new StreamOutter(process.getErrorStream(), "ERROR");
// any output?
StreamOutter outputGobbler = new StreamOutter(process.getInputStream(), "OUTPUT");

// kick them off
errorGobbler.start();
outputGobbler.start();
// command exit
process.waitFor();
public class StreamOutter extends Thread {
    InputStream is;
    String type;

    public StreamOutter(InputStream is, String type) {
        this.is = is;
        this.type = type;
    }

    public void run() {
        System.out.println("進入" + type + "處理線程");
        BufferedReader br = null;
        try {

            InputStreamReader isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line;
            System.out.println("開始處理" + type + "線程數據");
            while ((line = br.readLine()) != null) {
                XxlJobLogger.log(line);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

2、如果按照1中寫了之后也可以采用BufferedReader的read方式來快速處理

 br = new BufferedReader(isr);
 int one = null;
 if((one=br.read()) != -1){
 System.out.println((char) one);
 }

br.read()是挨個取出所有字符,所以需要進行對one進行拼接后在使用\n進行拆分,有點類似於,一次性讀出文件的所有內容的方式,需要自己進行處理后得到行數據

我這里使用第一種方式已經沒有問題了,至於第二種方式則需要自行探索了,如果有使用第二中方式解決的同學,可以指點一二;

二、Spring Boot通過命令行傳入的參數

方式一:

java -jar xxx.jar aaa bbb cccc

傳了3個參數,分別是aaa,bbb,ccc

通過main方法的參數獲取

方式二:

java -jar xxx.jar --test.test=aaa --domain=bbb

是springboot的寫法,可以通過@Value("${test.test}")@Value("${domain}") 獲取

個人博客 蝸牛


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM