【问题标题】:Scala JSR223 script using JMeter/Java context使用 JMeter/Java 上下文的 Scala JSR223 脚本
【发布时间】:2019-07-30 08:04:16
【问题描述】:

Scala JSR223 script support since 2.11

e.eval("""s"a is $a, s is $s"""")

我添加了 Scala 2.13 jars 并尝试执行脚本,它可以显示常量作为响应

但我无法将 JMeter 的绑定变量添加为 log,我尝试使用:

log.info(a);
$log.info(a);

或者不能打印值来记录,也试过了

var a:Int =  10
println(a)

JMeter 的bindings 代码:

 Bindings bindings = engine.createBindings();
 final Logger logger = LoggerFactory.getLogger(JSR223_INIT_FILE);
 bindings.put("log", logger); // $NON-NLS-1$ (this name is fixed)       
 engine.eval(reader, bindings);

也尝试使用绑定,但它不在上下文中

bindings.get("log").info("aa");

例外

ERROR o.a.j.p.j.s.JSR223Sampler: Problem in JSR223 script JSR223 Sampler, message: javax.script.ScriptException: not found: value bindings

如何使用 JMeter/Java 绑定变量提交 Scala JSR223 脚本?

编辑

打开Scala issueJSR223 - 引擎忽略绑定参数

【问题讨论】:

  • 奇数。当我自己尝试时,我发现根本没有注册的 ScriptEngineFactory 实例。
  • @MarkKegel 您是否将最新的 jars 添加到类路径中?
  • 哦。这就是问题所在。

标签: java scala jmeter jsr223 scriptengine


【解决方案1】:

问题的核心是注入的绑定被 Scala 脚本引擎视为具有Any 的类型。要使用注入的绑定,您必须在每次使用时将它们强制转换为适当的类型,或者您需要将它们作为“影子绑定”注入,然后使用适当的类型在引擎内重新绑定。

这是我的Main.scala,我在这里演示后一种方法:

import javax.script.ScriptEngineManager

import org.slf4j.Logger
import org.slf4j.LoggerFactory

object Main extends App {

  val logger: Logger = LoggerFactory.getLogger("main")

  val e = new ScriptEngineManager().getEngineByName("scala")
  e.put("a", 1)
  e.put("s", "String")

  // Since the variable will have a type of Object, inject under a different name, and then bind to the
  // "correct" name using eval.
  e.put("logInjected", logger)

  println(e.eval(""" s"a is $a, s is $s" """))
  println(e.eval(""" logInjected.toString """))

  e.eval(""" val log = logInjected.asInstanceOf[org.slf4j.Logger] """)
  e.eval(""" log.info("hello from injected logger") """)

  e.eval(
    """ // Or can you do this
      | import org.slf4j.Logger
      | import org.slf4j.LoggerFactory
      |
      | val l = LoggerFactory.getLogger("script")
      |
      | l.error("hello from script")
      |
      |""".stripMargin)
}

还有我以前的build.sbt

name := "s213"

version := "1.0"

scalaVersion in ThisBuild := "2.13.0"

libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value
libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.3.0-alpha4"
libraryDependencies += "org.slf4j" % "slf4j-api" % "2.0.0-alpha0"

运行Main 的输出将是:

a is 1, s is String
Logger[main]
[main] INFO  main - hello from injected logger 
[main] ERROR script - hello from script 

【讨论】:

  • 所以添加到bindings的变量在使用engine.eval(reader, bindings)时被忽略/不能在scala中使用?不是bug吗?
猜你喜欢
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
相关资源
最近更新 更多