Groovy Shell脚本对象未完全执行 [英] Groovy Shell script object not executed entirely

查看:296
本文介绍了Groovy Shell脚本对象未完全执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在创建一个普通的shell对象,然后将绑定传递给shell 使用shell解析groovy代码并初始化Script对象,如下所示

we are creating a groovy shell object and passing the bindings to the shell then the parsing the groovy code using the shell and initializing a Script object as below

GroovyShell shell = new GroovyShell(binding); 
Script script = shell.parse(//groovy code ); 

然后,我们将脚本对象存储在Concurrent哈希图中,并使用script.run()运行脚本,以从此哈希图中获取脚本,但是脚本中的常规代码并未完全执行,例如100次运行.我们已经在//groovy代码中放置了日志,该代码显示代码没有完全运行并且没有引发任何异常

then we are storing the script object in a Concurrent hashmap and running the script using script.run() fetching the script from this hashmap , But the groovy code in the script does not executes completely say 1 in 100 runs . we had placed logs in the //groovy code that shows the code did not run completely and neither any exception is thrown

推荐答案

当您同时在不同线程中运行同一脚本实例时,仅通过脚本逻辑即可停止该脚本实例.

when you run the same instance of Script in different threads at the same time it could be stopped just by logic of your script.

如果要缓存已解析的脚本,则将已解析的类而不是脚本的实例存储到映射中,并针对每次运行重新绑定变量.

if you want ta cache the parsed script, then store into your map the parsed class and not the instance of script and for each run re-bind variables.

以下代码段应为您提供一个实现方法:

the following code snippet should give you an idea how to do that:

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

这篇关于Groovy Shell脚本对象未完全执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆