我一直在使用Nashorn进行类似awk的批量数据处理。这个想法是,有很多传入数据,一个接一个地接一个接一个地传来。并且每一行都包含命名字段。这些数据由用户定义的脚本处理,这些脚本存储在外部某个位置,并且可由用户编辑。脚本很简单,例如if( c>10) a=b+3
,其中a,b和c是传入数据行中的字段。数据量确实很大。代码就是这样(显示用例的示例):
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
new String[]{"-strict", "--no-java", "--no-syntax-extensions", "--optimistic-types=true"},
null,
scr -> false);
CompiledScript cs;
Invocable inv=(Invocable) engine;
Bindings bd=engine.getBindings(ScriptContext.ENGINE_SCOPE);
bd.remove("load");
bd.remove("loadWithNewGlobal");
bd.remove("exit");
bd.remove("eval");
bd.remove("quit");
String scriptText=readScriptText();
cs = ((Compilable) engine).compile("function foo() {\n"+scriptText+"\n}");
cs.eval();
Map params=readIncomingData();
while(params!=null)
{
Map<String, Object> res = (Map) inv.invokeFunction("foo", params);
writeProcessedData(res);
params=readIncomingData();
}
现在nashorn已过时,我正在寻找替代方案。谷歌搜索了几天,但没有找到与我的需求完全匹配的东西。要求是:
很高兴拥有:
到目前为止,我发现Rhino仍然存在(最新版本为2020年1月13日),但我不确定它是否仍受支持以及它的运行速度-我记得,Java切换到Nashorn的原因之一是速度。在我看来,速度非常重要。还发现了J2V8,但不支持linux。 GraalVM看起来有些过大,还没有获得如何将其用于此类任务的信息-也许需要进一步研究它是否适合这样做,但是看起来它是完全的jvm替代品,不能用作库。
没有必要使用javascript,也许还有其他选择。谢谢。
GraalVM的JavaScript可以用作库,其依赖关系可以作为任何Maven工件获得。虽然建议的运行方式是使用GraalVM发行版,但有一些解释how to run it on OpenJDK。
您可以限制脚本应具有的访问权限,例如Java类,创建线程等:
The following access parameters may be configured:
* Allow access to other languages using allowPolyglotAccess.
* Allow and customize access to host objects using allowHostAccess.
* Allow and customize host lookup to host types using allowHostLookup.
* Allow host class loading using allowHostClassLoading.
* Allow the creation of threads using allowCreateThread.
* Allow access to native APIs using allowNativeAccess.
* Allow access to IO using allowIO and proxy file accesses using fileSystem.
而且它比Nashorn快几倍。例如,可以在此article中找到一些测量值:
GraalVM CE provides performance comparable or superior to Nashorn with
the composite score being 4 times higher. GraalVM EE is even faster.