对于Java应用程序,是否有更好的方法来支持基于自定义DSL的配置文件(例如依赖于Groovy或Kotlin)而不是使用JSR223 ScriptEngine
的eval
或compile
方法?
将脚本的内容加载为String
,然后在类似的代码中使用它,但也许有更好,更有效的方法。
String type = "groovy"; // or "kts"
String script = "..."; // code of DSL script
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension(type);
Compilable compiler = (Compilable) engine;
CompiledScript code = compiler.compile(script);
Object result = code.eval();
实际上作为JMeter,您应该将编译后的脚本保存在缓存中并使用它:
CompiledScript compiledScript = compiledScriptsCache.get(newCacheKey);
ScriptEngine也是如此
您可以跨线程共享ScriptEngine和CompiledScript对象。它们是线程安全的。实际上,您应该共享它们,因为单个引擎实例是类缓存和JavaScript对象的隐藏类的持有者,因此只有一个可以减少重复编译。