本文整理汇总了Scala中kafka.consumer.KafkaStream类的典型用法代码示例。如果您正苦于以下问题:Scala KafkaStream类的具体用法?Scala KafkaStream怎么用?Scala KafkaStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了KafkaStream类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: KafkaConsumer
//设置package包名称以及导入依赖的类
package services
import java.util.Properties
import akka.actor.{Props, Actor}
import kafka.consumer.{KafkaStream, Consumer, ConsumerConfig}
import play.Logger
object KafkaConsumer {
def props(topic: String): Props = Props(new KafkaConsumer(topic))
}
class KafkaConsumer(topic: String) extends Actor {
val props = new Properties()
props.put("auto.commit", "true")
//props.put("zookeeper.connect", "localhost:2181")
props.put("zookeeper.connect", "zookeeper1:2181")
def receive = {
case group: String => {
props.put("group.id", group)
val connector = Consumer.create(new ConsumerConfig(props))
val stream: KafkaStream[Array[Byte], Array[Byte]] = connector.createMessageStreams(Map(topic -> 1)).get(topic).get(0)
try {
for (message <- stream) {
try {
Logger.debug(new String(message.message()))
} catch {
case e: Throwable => Logger.error("error processing message, skipping and resume consumption: " + e)
}
}
}
}
}
}
示例2: ConsumerRunner
//设置package包名称以及导入依赖的类
package com.rockiey.kafka
import kafka.consumer.KafkaStream
class ConsumerRunner(stream: KafkaStream[Array[Byte], Array[Byte]],
val threadNumber: Int) extends Runnable {
override def run(): Unit = {
val it = stream.iterator()
println(s"Thread $threadNumber started")
while (it.hasNext()) {
val msg = new String(it.next().message())
println(System.currentTimeMillis() + ",Thread " + threadNumber + ": " + msg)
}
println(s"Thread $threadNumber stopped")
}
}