Nashorn的沙盒Java脚本替换

我一直在使用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已过时,我正在寻找替代方案。搜寻了几天,但没有找到符合我需求的精确匹配。要求是:

  • 速度。有很多数据,因此它应该很快。所以我也认为,必须进行预编译
  • 应在linux / openJDK下工作
  • 至少为数据访问/代码执行支持沙箱

很好玩:

  • 简单的类似c的语法(不是lua;)
  • 支持沙盒处理以提高CPU使用率

到目前为止,我发现Rhino仍然存在(最新版本为2020年1月13日),但是我不确定它是否仍受支持以及它的运行速度如何-我记得,Java切换到Nashorn的原因之一是速度。在我看来,速度非常重要。还发现了J2V8,但不支持linux。 GraalVM看起来有点矫kill过正,也还没有获得如何将其用于此类任务的信息-也许需要进一步探索它是否适合这样做,但看起来它是完全的jvm替代品,不能用作库。

没有必要使用javascript,也许还有其他选择。 谢谢。

cjz7366 回答:Nashorn的沙盒Java脚本替换

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. 
本文链接:https://www.f2er.com/2595168.html

大家都在问