How to expose Java method for Kafka (commitSync wi

2019-01-20 21:13发布

问题:

I am trying to expose Java method via Scala (more details on original java method - it is coming from Kafka)

This is original Java method:

public void commitSync(Map<TopicPartition,OffsetAndMetadata> offsets)

How to expose and pass parameters to a method in Scala? I have something like:

def commitSync() = {
     consumer.commitSync(...)
}

Thanks.

回答1:

Your Scala snippet looks correct, this is how I'd fill up the rest of it:

import org.apache.kafka.clients.consumer.{KafkaConsumer, OffsetAndMetadata}
import org.apache.kafka.common.TopicPartition

import collection.mutable.Map
import collection.JavaConverters._

//initialise your consumer the way you want
val consumer = createKafkaConsumer(config, subscriptions)

//you could accept a scala.collection.mutable.Map here
def commitSync(offsets: Map[TopicPartition, OffsetAndMetadata]) = {
    //and then convert it to a java.util.Map
    consumer.commitSync(offsets.asJava)
}