![](/img/trans.png)
[英]Failure to load properly Groovy library into Groovy shell executing script
[英]Groovy Shell script object not executed entirely
我们正在创建一个 groovy shell 对象并将绑定传递给 shell,然后使用 shell 解析 groovy 代码并初始化一个Script
对象,如下所示
GroovyShell shell = new GroovyShell(binding);
Script script = shell.parse(//groovy code );
然后我们将脚本对象存储在 Concurrent hashmap 中,并使用script.run()
运行脚本,从这个 hashmap 中获取脚本,但是脚本中的 groovy 代码并没有完全执行,比如 100 次运行中的 1 次。 我们在 //groovy 代码中放置了日志,显示代码没有完全运行,也没有抛出任何异常
当您同时在不同线程中运行相同的 Script 实例时,它可能会被您的脚本逻辑停止。
如果您想缓存解析后的脚本,则将解析后的类而不是脚本实例存储到您的映射中,并为每次运行重新绑定变量。
下面的代码片段应该让你知道如何做到这一点:
scriptMap = new HashMap()
Script getScript(String code){
Class<Script> scriptClass = scriptMap.get(code);
if(scriptClass)return script.newInstance();
GroovyShell shell = new GroovyShell();
Script script = shell.parse( code );
scriptMap.put(code, script.getClass());
return script;
}
Object runScript(String code, Map variables){
Script script=getScript(code);
script.setBinding( new Binding(variables) );
return script.run();
}
println runScript("a+b", [a:2,b:7])
println runScript("(b-a)*3", [a:7,b:9])
println scriptMap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.