scala中的bug在尝试遍历消费者记录时,为每个循环输入

uurv41yg  于 2021-06-06  发布在  Kafka
关注(0)|答案(2)|浏览(354)

无法解析foreach的符号

import java.util._
import org.apache.kafka.clients.consumer._
import org.apache.kafka.common.serialization.Deserializer

object ConsumerExample {

  def main(args: Array[String]): Unit = {

    val T_Name = "CarSensor"
    val T_Group_Name = "CarSensorGroup"
    val props = new Properties()

    props.put("bootstrap.servers", "localhost:9092,localhost:9093,localhost:9094")
    props.put("group.id",T_Group_Name)
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")

    val Kafka_Consumer=new KafkaConsumer[String,String](props)
    Kafka_Consumer.subscribe (Arrays.asList(T_Name))
    while(true)
    {
      val Consumer_Record=Kafka_Consumer.poll(100) //ConsumerRecords Object
      //  val RecordList=Consumer_Record.toString
      for( i <- Consumer_Record)
      { //**This place is where Cannot resolve symbol for Foreach issue shows up for <- symbol.**
        println("Supplier id = "+String.valueOf(i.value().getID())+ "Supplier name = " +i.value().getID())
      }
    }
  }
}

在它起作用之前,我已经在许多例子中使用了<-symbol。我认为这是intelliji的问题,于是重新启动了它。这是一个问题,在对象得到铸造不同的类型,我想。

fumotvh3

fumotvh31#

Consumer_Record.forEach(i => {
    println("Supplier id = "+String.valueOf(i.value().getID())+ "Supplier name = " +i.value().getID())
  })

对我来说很好。
除外 String 没有 getID() 方法。
你可以用 for(i <- Consumer_Record.asScala) 如果你愿意的话 for 语法,但您必须添加 import scala.collection.JavaConverters._ .

3bygqnnd

3bygqnnd2#

val Kafka_Consumer=new KafkaConsumer[String,String](props)

Kafka_Consumer.subscribe(Arrays.asList(T_Name))

while(true) {

  val Consumer_Record=Kafka_Consumer.poll(100) //ConsumerRecords Object

  for( i <- Consumer_Record.asScala) {
    println("Supplier id = "+String.valueOf(i.value())+ " Supplier name = " +i.key())
  }
}

相关问题