允许缓存和编译的 JMeter 脚本引擎

JMeter Script Engine which allow caching and compilation

JSR223 Sampler 声明 Groovy 实现 Compilable interface 不同于其他脚本语言,因此推荐

To benefit from caching and compilation, the language engine used for scripting must implement JSR223 Compilable interface (Groovy is one of these, java, beanshell and javascript are not)

我尝试在 JSR223 采样器中使用 similar code 来检查它。 我尝试使用 Compilable:

检查所有可用的语言
import javax.script.Compilable;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
ScriptEngineManager mgr = new ScriptEngineManager();
    engineFactories = mgr.getEngineFactories();
    for (ScriptEngineFactory engineFactory : engineFactories) {

        if (engineFactory instanceof Compilable) {
              log.info(engineFactory.getEngineName() + " Script compilation is supported.");
            } else {
              log.info(engineFactory.getEngineName() + " Script compilation is not supported.");
            }
    }

我的结果是:

Oracle Nashorn Script compilation is not supported.
JEXL Engine Script compilation is not supported.
Groovy Scripting Engine Script compilation is not supported.
JEXL Engine Script compilation is not supported.
Velocity Script compilation is not supported.
BeanShell Engine Script compilation is not supported.

含义none支持编译,

编辑 1 我根据@aristotll 更改了检查,现在 returns all 支持编译

final ScriptEngine engine = engineFactory.getScriptEngine();
if (engine instanceof Compilable) {

编辑 2

我根据@aristotll 二次编辑修改

try {
            ((Compilable) engine).compile("");
                        log.info(engineFactory.getEngineName() + " Script compilation is supported.");
        } catch (Error e) {
            log.info(engineFactory.getEngineName() + " Script compilation is not supported.");

我得到了有趣的结果:Nashorn 和 JEXL 支持它

Groovy Scripting Engine Script compilation is supported.
Oracle Nashorn Script compilation is supported.
JEXL Engine Script compilation is supported.
BeanShell Engine Script compilation is not supported.
JEXL Engine Script compilation is supported.

我是不是查错了?我需要导入更多的罐子来启用它吗? 我怎么知道脚本引擎是否使用缓存和编译? JMeter 的语句是 wrong/outdated ?

您需要获取 ScriptEngine 实例而不是 ScriptEngineFactory

final ScriptEngine engine = engineFactory.getScriptEngine();
if (engine instanceof Compilable) {
...

为什么都是Compilable?因为这些脚本引擎将来可能是可编译的。但是目前不支持,所以都实现了这个接口。 您可以尝试编译空字符串:

  if (engine instanceof Compilable) {
        try {
            ((Compilable) engine).compile("");
        } catch (Error e) {
            System.out.println(engineName + " Script compilation is not supported.");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        System.out.println(engineName + " Script compilation is supported.");
    } else {
        System.out.println(engineName + " Script compilation is not supported.");
    }