Nashorn 的沙盒 java 脚本替代品

Sandboxed java scripting replacement for Nashorn

我一直在使用 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 类、创建线程等:

来自documentation

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.