Skip to main content
 首页 » 编程设计

python之使用 Python 的 Spring 集成脚本

2024年10月24日21傻小

我正在尝试将 Python 与 spring-integration 和 jython-standalone-2.7.0 结合使用:

这是我的应用程序上下文:

<int:inbound-channel-adapter id="in" channel="exampleChannel" > 
    <int:poller fixed-rate="1000" /> 
    <int-script:script lang="python" location="script/message.py" /> 
</int:inbound-channel-adapter> 
 
<int:channel id="exampleChannel" /> 
<int-ip:udp-outbound-channel-adapter id="udpOut" channel="exampleChannel" host="192.168.0.1" port="11111" /> 

这是我的 Python 脚本:

print "Python" 
message="python-message" 

当我启动应用程序时,我在控制台中看到“Python”。这一定意味着我的脚本是由 spring-integration 启动的,但没有在 udp 中发送任何内容。

我在 org.spring.framework.integration.scripting.js223.AbstractScriptExecutor 的代码中看到:

result = scriptEngine.eval(script, new SimpleBindings(variables)); 

所有 Python 变量都在 Map 变量中,scriptEngine 不包含对 Python 变量的引用。

因此,在org.spring.framework.integration.scripting.js223.PythonScriptExecutor中:

scriptEngine.get(returnVariableName); 

它返回空值。

这是 Jython、Spring 集成中的问题还是我做错了什么?

请您参考如下方法:

这是Spring Integration中的一个bug;我开了一个JIRA Issue .

        if (variables != null) { 
            result = scriptEngine.eval(script, new SimpleBindings(variables)); 
        } 
        else { 
            result = scriptEngine.eval(script); 
        } 

当执行 if 测试的第一个分支时,结果变量被添加到 SimpleBindings 对象中,而不是添加到引擎范围映射中。

即使在您的情况下变量为空,我们仍会调用第一个分支。

编辑:

在我们修复错误之前,这是一个变通方法...

public class Foo { 
 
    private final ScriptExecutor executor = ScriptExecutorFactory.getScriptExecutor("python"); 
 
    private final ScriptSource source = new ResourceScriptSource(new ClassPathResource("/message.py")); 
 
    public String script() { 
        return (String) this.executor.executeScript(source); 
    } 
 
} 

和

<int:inbound-channel-adapter id="in" channel="exampleChannel" method="script"> 
    <int:poller fixed-rate="1000" /> 
    <bean class="foo.Foo" /> 
</int:inbound-channel-adapter>