目录
springboot调用python脚本
准备工作
方法一:使用 ProcessBuilder
1. 编写测试方法
2. 解释代码
方法二:使用 Apache Commons Exec
1. 编写测试方法
2. 解释代码
Python 脚本的数据通过接口让 Spring Boot 接收。
Python 脚本作为服务
1. 使用 Flask 创建 Python HTTP 服务
2. 在 Spring Boot 中调用 Python HTTP 服务
使用 RestTemplate
使用 WebClient
结论
在现代软件开发中,有时我们需要在 Java 应用中调用外部脚本,比如 Python 脚本。Spring Boot 提供了灵活的方式来集成这些外部脚本。本文将详细介绍如何在 Spring Boot 应用中调用 Python 脚本,包括两种不同的方法:使用 Java 的 ProcessBuilder
类和使用 Apache Commons Exec 库。
在开始之前,我们需要准备一个 Python 脚本。请按照以下步骤操作:
python
的文件夹。hello.py
的 Python 脚本,内容如下:python
print("Hello World!!")
java
private static final String PATH = "D:\\python\\hello.py";
ProcessBuilder
是 Java 提供的一个类,允许我们启动和管理操作系统进程。以下是使用 ProcessBuilder
调用 Python 脚本的步骤:
在 Spring Boot 应用中,我们可以编写一个测试方法来调用 Python 脚本:
java
@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);
}
ProcessBuilder
构造函数接受要执行的命令和参数。这里,我们传递了 "python"
和脚本路径 PATH
。redirectErrorStream(true)
将错误流和标准流合并,这样我们可以从同一个流中读取输出。processBuilder.start()
启动进程。BufferedReader
读取进程的输出。process.waitFor()
等待进程结束,并返回退出代码。Apache Commons Exec 提供了一个更高级的 API 来执行外部进程。首先,我们需要在项目的 pom.xml
文件中添加依赖:
xml
org.apache.commons
commons-exec
1.3
使用 Apache Commons Exec 调用 Python 脚本的代码如下:
java
@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脚本的执行结果: {}.", exitCode == 0 ? "成功" : "失败");
log.info(baos.toString().trim());
} catch (final IOException e) {
log.error("调用Python脚本出错", e);
}
}
CommandLine.parse(line)
解析要执行的命令。PumpStreamHandler
将输出流重定向到 ByteArrayOutputStream
。DefaultExecutor
用于执行命令。executor.execute(cmdLine)
执行命令并返回退出代码。log.info
和 log.error
用于记录执行结果和错误。为了让 Spring Boot 能够接收 Python 脚本的数据,我们可以将 Python 脚本包装成一个 HTTP 服务。这样,Spring Boot 可以通过 HTTP 请求来调用 Python 脚本,并接收其返回的数据。以下是实现这一目标的步骤:
首先,我们需要在 Python 脚本中添加 Flask 库来创建一个简单的 HTTP 服务。以下是修改后的 hello.py
:
python
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)
这段代码创建了一个 Flask 应用,它在 5000
端口上运行,并定义了一个 /hello
路由,返回一个 JSON 响应。
现在,我们需要在 Spring Boot 应用中调用这个 Python HTTP 服务。我们可以使用 RestTemplate
或 WebClient
来发送 HTTP 请求。
在 Spring Boot 中,你可以添加 RestTemplate
的依赖:
xml
org.springframework.boot
spring-boot-starter-web
然后,创建一个服务来调用 Python 服务:
java
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;
}
}
如果你使用的是 Spring WebFlux,可以使用 WebClient
:
java
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 脚本,并接收其返回的数据。这种方法不仅适用于 Python 脚本,还可以用于任何可以提供 HTTP 接口的外部服务。这样,Spring Boot 应用就可以通过标准的 HTTP 请求与这些服务进行交互,实现数据的集成和处理。