springboot調(diào)用python腳本的實(shí)現(xiàn)示例
在現(xiàn)代軟件開發(fā)中,有時(shí)我們需要在 Java 應(yīng)用中調(diào)用外部腳本,比如 Python 腳本。Spring Boot 提供了靈活的方式來集成這些外部腳本。本文將詳細(xì)介紹如何在 Spring Boot 應(yīng)用中調(diào)用 Python 腳本,包括兩種不同的方法:使用 Java 的 ProcessBuilder
類和使用 Apache Commons Exec 庫(kù)。
準(zhǔn)備工作
在開始之前,我們需要準(zhǔn)備一個(gè) Python 腳本。請(qǐng)按照以下步驟操作:
- 在 D 盤創(chuàng)建一個(gè)名為
python
的文件夾。 - 在該文件夾內(nèi)創(chuàng)建一個(gè)名為
hello.py
的 Python 腳本,內(nèi)容如下:
print("Hello World!!")
- 在 Spring Boot 項(xiàng)目中定義 Python 腳本的路徑:
private static final String PATH = "D:\\python\\hello.py";
方法一:使用 ProcessBuilder
ProcessBuilder
是 Java 提供的一個(gè)類,允許我們啟動(dòng)和管理操作系統(tǒng)進(jìn)程。以下是使用 ProcessBuilder
調(diào)用 Python 腳本的步驟:
1. 編寫測(cè)試方法
在 Spring Boot 應(yīng)用中,我們可以編寫一個(gè)測(cè)試方法來調(diào)用 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
構(gòu)造函數(shù)接受要執(zhí)行的命令和參數(shù)。這里,我們傳遞了"python"
和腳本路徑PATH
。redirectErrorStream(true)
將錯(cuò)誤流和標(biāo)準(zhǔn)流合并,這樣我們可以從同一個(gè)流中讀取輸出。processBuilder.start()
啟動(dòng)進(jìn)程。- 使用
BufferedReader
讀取進(jìn)程的輸出。 process.waitFor()
等待進(jìn)程結(jié)束,并返回退出代碼。
方法二:使用 Apache Commons Exec
Apache Commons Exec 提供了一個(gè)更高級(jí)的 API 來執(zhí)行外部進(jìn)程。首先,我們需要在項(xiàng)目的 pom.xml
文件中添加依賴:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-exec</artifactId> <version>1.3</version> </dependency>
1. 編寫測(cè)試方法
使用 Apache Commons Exec 調(diào)用 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("調(diào)用Python腳本的執(zhí)行結(jié)果: {}.", exitCode == 0 ? "成功" : "失敗"); log.info(baos.toString().trim()); } catch (final IOException e) { log.error("調(diào)用Python腳本出錯(cuò)", e); } }
2. 解釋代碼
CommandLine.parse(line)
解析要執(zhí)行的命令。PumpStreamHandler
將輸出流重定向到ByteArrayOutputStream
。DefaultExecutor
用于執(zhí)行命令。executor.execute(cmdLine)
執(zhí)行命令并返回退出代碼。log.info
和log.error
用于記錄執(zhí)行結(jié)果和錯(cuò)誤。
Python 腳本的數(shù)據(jù)通過接口讓 Spring Boot 接收
Python 腳本作為服務(wù)
為了讓 Spring Boot 能夠接收 Python 腳本的數(shù)據(jù),我們可以將 Python 腳本包裝成一個(gè) HTTP 服務(wù)。這樣,Spring Boot 可以通過 HTTP 請(qǐng)求來調(diào)用 Python 腳本,并接收其返回的數(shù)據(jù)。以下是實(shí)現(xiàn)這一目標(biāo)的步驟:
1. 使用 Flask 創(chuàng)建 Python HTTP 服務(wù)
首先,我們需要在 Python 腳本中添加 Flask 庫(kù)來創(chuàng)建一個(gè)簡(jiǎn)單的 HTTP 服務(wù)。以下是修改后的 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)建了一個(gè) Flask 應(yīng)用,它在 5000
端口上運(yùn)行,并定義了一個(gè) /hello
路由,返回一個(gè) JSON 響應(yīng)。
2. 在 Spring Boot 中調(diào)用 Python HTTP 服務(wù)
現(xiàn)在,我們需要在 Spring Boot 應(yīng)用中調(diào)用這個(gè) Python HTTP 服務(wù)。我們可以使用 RestTemplate
或 WebClient
來發(fā)送 HTTP 請(qǐng)求。
使用 RestTemplate
在 Spring Boot 中,你可以添加 RestTemplate
的依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
然后,創(chuàng)建一個(gè)服務(wù)來調(diào)用 Python 服務(wù):
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(); } }
結(jié)論
通過將 Python 腳本包裝成 HTTP 服務(wù),我們可以更容易地在 Spring Boot 應(yīng)用中調(diào)用 Python 腳本,并接收其返回的數(shù)據(jù)。這種方法不僅適用于 Python 腳本,還可以用于任何可以提供 HTTP 接口的外部服務(wù)。這樣,Spring Boot 應(yīng)用就可以通過標(biāo)準(zhǔn)的 HTTP 請(qǐng)求與這些服務(wù)進(jìn)行交互,實(shí)現(xiàn)數(shù)據(jù)的集成和處理。
到此這篇關(guān)于springboot調(diào)用python腳本的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)springboot調(diào)用python腳本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring框架基于xml實(shí)現(xiàn)自動(dòng)裝配流程詳解
自動(dòng)裝配就是指?Spring?容器在不使用?<constructor-arg>?和<property>?標(biāo)簽的情況下,可以自動(dòng)裝配(autowire)相互協(xié)作的?Bean?之間的關(guān)聯(lián)關(guān)系,將一個(gè)?Bean?注入其他?Bean?的?Property?中2022-11-11在idea中設(shè)置項(xiàng)目編碼格式為UTF-8的操作方法
idea中的默認(rèn)編碼為GBK,在開發(fā)過程中一般將編碼格式改為UTF-8,所以本文給大家介紹了在idea中設(shè)置項(xiàng)目編碼為UTF-8的操作方法,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12java實(shí)現(xiàn)請(qǐng)求緩沖合并的示例代碼
我們對(duì)外提供了一個(gè)rest接口給第三方業(yè)務(wù)進(jìn)行調(diào)用,但是由于第三方框架限制,導(dǎo)致會(huì)發(fā)送大量相似無(wú)效請(qǐng)求,這篇文章主要介紹了java實(shí)現(xiàn)請(qǐng)求緩沖合并,需要的朋友可以參考下2024-04-04使用Java實(shí)現(xiàn)通用樹形結(jié)構(gòu)構(gòu)建工具類
這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)通用樹形結(jié)構(gòu)構(gòu)建工具類,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-03-03JavaWeb Spring注解Annotation深入學(xué)習(xí)
這篇文章主要為大家詳細(xì)介紹了JavaWeb Spring注解Annotation,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09