@@ -6,9 +6,9 @@ import org.apache.log4j.Logger
66
77import scala .util .Try
88
9- /** Method extensions for Kafka's [[KafkaConsumer ]] API allowing easy testing.*/
9+ /** Method extensions for Kafka's [[KafkaConsumer ]] API allowing easy testing. */
1010object ConsumerExtensions {
11- val MaximumAttempts = 3
11+
1212 implicit class ConsumerOps [K , V ](val consumer : KafkaConsumer [K , V ]) {
1313
1414 private val logger = Logger .getLogger(classOf [ConsumerOps [K , V ]])
@@ -18,14 +18,16 @@ object ConsumerExtensions {
1818 * to consume batches from the given topic, until it reaches the number of desired messages or
1919 * return otherwise.
2020 *
21- * @param topic the topic from which to consume messages
21+ * @param topic the topic from which to consume messages
22+ * @param maximumAttempts the maximum number of attempts to try and get the batch (defaults to 3)
23+ * @param poll the amount of time, in milliseconds, to wait in the buffer for any messages to be available (defaults to 2000)
2224 * @return the stream of consumed messages that you can do `.take(n: Int).toList`
2325 * to evaluate the requested number of messages.
2426 */
25- def consumeLazily (topic : String ): Stream [(K , V )] = {
26- val attempts = 1 to MaximumAttempts
27+ def consumeLazily (topic : String , maximumAttempts : Int = 3 , poll : Long = 2000 ): Stream [(K , V )] = {
28+ val attempts = 1 to maximumAttempts
2729 attempts.toStream.flatMap { attempt =>
28- val batch : Seq [(K , V )] = getNextBatch(topic)
30+ val batch : Seq [(K , V )] = getNextBatch(topic, poll )
2931 logger.debug(s " ----> Batch $attempt ( $topic) | ${batch.mkString(" |" )}" )
3032 batch
3133 }
@@ -34,18 +36,20 @@ object ConsumerExtensions {
3436 /** Get the next batch of messages from Kafka.
3537 *
3638 * @param topic the topic to consume
39+ * @param poll the amount of time, in milliseconds, to wait in the buffer for any messages to be available
3740 * @return the next batch of messages
3841 */
39- def getNextBatch (topic : String ): Seq [(K , V )] =
42+ private def getNextBatch (topic : String , poll : Long ): Seq [(K , V )] =
4043 Try {
41- import scala .collection .JavaConversions ._
42- consumer.subscribe(List (topic))
44+ import scala .collection .JavaConverters ._
45+ consumer.subscribe(List (topic).asJava )
4346 consumer.partitionsFor(topic)
44- val records = consumer.poll(2000 )
47+ val records = consumer.poll(poll )
4548 // use toList to force eager evaluation. toSeq is lazy
46- records.iterator().toList.map(r => r.key -> r.value)
49+ records.iterator().asScala. toList.map(r => r.key -> r.value)
4750 }.recover {
4851 case ex : KafkaException => throw new KafkaUnavailableException (ex)
4952 }.get
5053 }
54+
5155}
0 commit comments