从Spring @Service运行Python脚本

时间:2017-07-06 11:40:20

标签: java python spring

我需要执行一个带有从我的用户界面传递的参数的python脚本并显示结果。我知道如何使用ProcessBuilder(下面)这样做,但我认为只是从相关的Spring @Service调用这个代码并不是一个好主意(线程问题,太多并发运行的实例等)。什么是最好的方法?

@Override
public String executeLatestAlgorithm(String json) {

    try {
        ProcessBuilder probuilder = new ProcessBuilder("somescript.py", json);
        Process p = probuilder.start();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        return in.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

(没有任何重大错误处理的废话代码 - 只是为了说明)

非常感谢,

A

1 个答案:

答案 0 :(得分:2)

显然,Spring Integration为执行用Python,JS,Groovy等编写的脚本提供支持。

https://github.com/spring-projects/spring-integration-samples/tree/master/applications/cafe-scripted

Python相关配置XML的一部分如下所示

<service-activator input-channel="hotDrinks"
    output-channel="preparedDrinks">
    <script:script lang="python" location="file:scripts/python/barista.py">
        <script:variable name="timeToPrepare" value="5" />
    </script:script>
</service-activator>