Gatling跨仿真数据共享:自定义队列Feeder编译错误排查求助
Hey there! Let's break down the compile error you're facing and fix it step by step.
1. 核心编译错误原因
The root cause of your compile error is a mistaken attempt to treat a String as an array:
session("AccountId").as[String][0]
session("AccountId").as[String] returns a single String value, not an array. Using [0] (array index syntax) on a String is invalid in Scala, which triggers the compiler error String does not take type parameters.
Your intent is clearly to add the AccountId and uuid strings as two elements of an array to the queue—so you don't need any index operators here.
2. Fix the Error Line
Replace the problematic line with this corrected version:
DequeHolder.DataDeque.offer(Array(session("AccountId").as[String], session("uuid").as[String]))
3. Additional Potential Fixes
There are two more adjustments needed to avoid future issues:
3.1 Fix Feeder Generic Mismatch
Your DataFeeder is declared as Feeder[String], but its next() method returns a Map[String, Array[String]]—this is a generic type mismatch. Update the Feeder's generic type to match the value you're returning:
class DataFeeder extends Feeder[Array[String]] { override def hasNext: Boolean = DequeHolder.DataDeque.size() > 0 override def next(): Map[String, Array[String]] = Map("data" -> DequeHolder.DataDeque.poll()) }
3.2 Avoid Resource Leaks (PrintWriter)
Your original code manually closes the PrintWriter, but if an exception occurs before the close() call, the stream could be left open. Use a try-finally block to ensure the resource is always released:
.exec { session => val accountId = session("AccountId").as[String] val uuid = session("uuid").as[String] val writer = new PrintWriter(new FileOutputStream(outputFilePath, true)) try { writer.write(s"$accountId,$uuid\n") } finally { writer.close() } session }
4. Full Corrected Code Snippet
// Step to write data to file .exec { session => val accountId = session("AccountId").as[String] val uuid = session("uuid").as[String] val writer = new PrintWriter(new FileOutputStream(outputFilePath, true)) try { writer.write(s"$accountId,$uuid\n") } finally { writer.close() } session } // Step to add data to shared queue .exec { session => val accountId = session("AccountId").as[String] val uuid = session("uuid").as[String] DequeHolder.DataDeque.offer(Array(accountId, uuid)) session } // Corrected shared feeder class DataFeeder extends Feeder[Array[String]] { override def hasNext: Boolean = DequeHolder.DataDeque.size() > 0 override def next(): Map[String, Array[String]] = Map("data" -> DequeHolder.DataDeque.poll()) }
内容的提问来源于stack exchange,提问作者Perf2017

