欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot調用python腳本的實現(xiàn)示例

 更新時間:2024年12月24日 09:20:20   作者:luckilyil  
本文介紹了在SpringBoot應用中調用Python腳本,包括ProcessBuilder類和ApacheCommonsExec庫兩種方法,具有一定的參考價值,感興趣的可以了解一下

在現(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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Maven scala和java混合打包方式

    Maven scala和java混合打包方式

    這篇文章主要介紹了Maven scala和java混合打包方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • SpringBoot集成支付寶沙箱支付(支付、退款)

    SpringBoot集成支付寶沙箱支付(支付、退款)

    這篇文章主要為大家詳細介紹了SpringBoot集成支付寶沙箱支付,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • Spring框架基于xml實現(xiàn)自動裝配流程詳解

    Spring框架基于xml實現(xiàn)自動裝配流程詳解

    自動裝配就是指?Spring?容器在不使用?<constructor-arg>?和<property>?標簽的情況下,可以自動裝配(autowire)相互協(xié)作的?Bean?之間的關聯(lián)關系,將一個?Bean?注入其他?Bean?的?Property?中
    2022-11-11
  • 在idea中設置項目編碼格式為UTF-8的操作方法

    在idea中設置項目編碼格式為UTF-8的操作方法

    idea中的默認編碼為GBK,在開發(fā)過程中一般將編碼格式改為UTF-8,所以本文給大家介紹了在idea中設置項目編碼為UTF-8的操作方法,文中通過圖文介紹的非常詳細,需要的朋友可以參考下
    2023-12-12
  • Java之SpringBoot-Thymeleaf詳情

    Java之SpringBoot-Thymeleaf詳情

    聊Thymeleaf,需要知道為什么到了SpringBoot中就不用JSP了?這跟SpringBoot打包方式有點關系,SpringBoot項目打包是jar包,下面文章小編就對此做一個詳細介紹,需要的朋友可以參考一下
    2021-09-09
  • java基礎之方法詳解

    java基礎之方法詳解

    這篇文章主要介紹了java基礎之方法詳解,文中有非常詳細的代碼示例,對正在學習java基礎的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-07-07
  • java實現(xiàn)請求緩沖合并的示例代碼

    java實現(xiàn)請求緩沖合并的示例代碼

    我們對外提供了一個rest接口給第三方業(yè)務進行調用,但是由于第三方框架限制,導致會發(fā)送大量相似無效請求,這篇文章主要介紹了java實現(xiàn)請求緩沖合并,需要的朋友可以參考下
    2024-04-04
  • Java8 Instant時間戳使用小記

    Java8 Instant時間戳使用小記

    這篇文章主要給大家介紹了關于Java8 Instant時間戳使用的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • 使用Java實現(xiàn)通用樹形結構構建工具類

    使用Java實現(xiàn)通用樹形結構構建工具類

    這篇文章主要為大家詳細介紹了如何使用Java實現(xiàn)通用樹形結構構建工具類,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2025-03-03
  • JavaWeb Spring注解Annotation深入學習

    JavaWeb Spring注解Annotation深入學習

    這篇文章主要為大家詳細介紹了JavaWeb Spring注解Annotation,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09

最新評論