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