对于 Java 应用程序来说,有没有比使用 JSR223 ScriptEngine
的 eval 更好的方法来支持基于自定义 DSL(例如依赖 Groovy 或 Kotlin)的配置文件
或 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
You can share a ScriptEngine and CompiledScript objects across threads. They are threadsafe. Actually, you should share them, as a single engine instance is a holder for a class cache and for JavaScript objects' hidden classes, so by having only one you cut down on repeated compilation.
关于java - 从 Java 应用程序加载自定义 DSL 配置的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759984/