springboot調用python腳本的實現(xiàn)示例
在現(xiàn)代軟件開發(fā)中,有時我們需要在 Java 應用中調用外部腳本,比如 Python 腳本。Spring Boot 提供了靈活的方式來集成這些外部腳本。本文將詳細介紹如何在 Spring Boot 應用中調用 Python 腳本,包括兩種不同的方法:使用 Java 的 ProcessBuilder
類和使用 Apache Commons Exec 庫。
準備工作
在開始之前,我們需要準備一個 Python 腳本。請按照以下步驟操作:
- 在 D 盤創(chuàng)建一個名為
python
的文件夾。 - 在該文件夾內(nèi)創(chuàng)建一個名為
hello.py
的 Python 腳本,內(nèi)容如下:
print("Hello World!!")
- 在 Spring Boot 項目中定義 Python 腳本的路徑:
private static final String PATH = "D:\\python\\hello.py";
方法一:使用 ProcessBuilder
ProcessBuilder
是 Java 提供的一個類,允許我們啟動和管理操作系統(tǒng)進程。以下是使用 ProcessBuilder
調用 Python 腳本的步驟:
1. 編寫測試方法
在 Spring Boot 應用中,我們可以編寫一個測試方法來調用 Python 腳本:
@Test public void testMethod1() throws IOException, InterruptedException { final ProcessBuilder processBuilder = new ProcessBuilder("python", PATH); processBuilder.redirectErrorStream(true); final Process process = processBuilder.start(); final BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String s = null; while ((s = in.readLine()) != null) { System.out.println(s); } final int exitCode = process.waitFor(); System.out.println(exitCode == 0); }
2. 解釋代碼
ProcessBuilder
構造函數(shù)接受要執(zhí)行的命令和參數(shù)。這里,我們傳遞了"python"
和腳本路徑PATH
。redirectErrorStream(true)
將錯誤流和標準流合并,這樣我們可以從同一個流中讀取輸出。processBuilder.start()
啟動進程。- 使用
BufferedReader
讀取進程的輸出。 process.waitFor()
等待進程結束,并返回退出代碼。
方法二:使用 Apache Commons Exec
Apache Commons Exec 提供了一個更高級的 API 來執(zhí)行外部進程。首先,我們需要在項目的 pom.xml
文件中添加依賴:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-exec</artifactId> <version>1.3</version> </dependency>
1. 編寫測試方法
使用 Apache Commons Exec 調用 Python 腳本的代碼如下:
@Test public void testMethod2() { final String line = "python " + PATH; final CommandLine cmdLine = CommandLine.parse(line); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { final PumpStreamHandler streamHandler = new PumpStreamHandler(baos); final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(streamHandler); final int exitCode = executor.execute(cmdLine); log.info("調用Python腳本的執(zhí)行結果: {}.", exitCode == 0 ? "成功" : "失敗"); log.info(baos.toString().trim()); } catch (final IOException e) { log.error("調用Python腳本出錯", e); } }
2. 解釋代碼
CommandLine.parse(line)
解析要執(zhí)行的命令。PumpStreamHandler
將輸出流重定向到ByteArrayOutputStream
。DefaultExecutor
用于執(zhí)行命令。executor.execute(cmdLine)
執(zhí)行命令并返回退出代碼。log.info
和log.error
用于記錄執(zhí)行結果和錯誤。
Python 腳本的數(shù)據(jù)通過接口讓 Spring Boot 接收
Python 腳本作為服務
為了讓 Spring Boot 能夠接收 Python 腳本的數(shù)據(jù),我們可以將 Python 腳本包裝成一個 HTTP 服務。這樣,Spring Boot 可以通過 HTTP 請求來調用 Python 腳本,并接收其返回的數(shù)據(jù)。以下是實現(xiàn)這一目標的步驟:
1. 使用 Flask 創(chuàng)建 Python HTTP 服務
首先,我們需要在 Python 腳本中添加 Flask 庫來創(chuàng)建一個簡單的 HTTP 服務。以下是修改后的 hello.py
:
from flask import Flask, jsonify app = Flask(__name__) @app.route('/hello', methods=['GET']) def hello_world(): return jsonify(message="Hello World!!") if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
這段代碼創(chuàng)建了一個 Flask 應用,它在 5000
端口上運行,并定義了一個 /hello
路由,返回一個 JSON 響應。
2. 在 Spring Boot 中調用 Python HTTP 服務
現(xiàn)在,我們需要在 Spring Boot 應用中調用這個 Python HTTP 服務。我們可以使用 RestTemplate
或 WebClient
來發(fā)送 HTTP 請求。
使用 RestTemplate
在 Spring Boot 中,你可以添加 RestTemplate
的依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
然后,創(chuàng)建一個服務來調用 Python 服務:
import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class PythonService { private static final String PYTHON_SERVICE_URL = "http://localhost:5000/hello"; public String callPythonService() { RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(PYTHON_SERVICE_URL, String.class); return result; } }
使用 WebClient
如果你使用的是 Spring WebFlux,可以使用 WebClient
:
import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; @Service public class PythonService { private static final String PYTHON_SERVICE_URL = "http://localhost:5000/hello"; private final WebClient webClient; public PythonService(WebClient.Builder webClientBuilder) { this.webClient = webClientBuilder.baseUrl(PYTHON_SERVICE_URL).build(); } public String callPythonService() { return webClient.get() .retrieve() .bodyToMono(String.class) .block(); } }
結論
通過將 Python 腳本包裝成 HTTP 服務,我們可以更容易地在 Spring Boot 應用中調用 Python 腳本,并接收其返回的數(shù)據(jù)。這種方法不僅適用于 Python 腳本,還可以用于任何可以提供 HTTP 接口的外部服務。這樣,Spring Boot 應用就可以通過標準的 HTTP 請求與這些服務進行交互,實現(xiàn)數(shù)據(jù)的集成和處理。
到此這篇關于springboot調用python腳本的實現(xiàn)示例的文章就介紹到這了,更多相關springboot調用python腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaWeb Spring注解Annotation深入學習
這篇文章主要為大家詳細介紹了JavaWeb Spring注解Annotation,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09