Slide 17
Slide 17 text
case class KafkaProducerConnector[K :ClassTag, V :ClassTag](
name: Symbol, config: java.util.Map[String, AnyRef])
extends Connector[ScalaKafkaProducer[K, V]] {
def get: ScalaKafkaProducer[K, V] =
KafkaProducerConnector.defaultHolder.getOrCreate(name, mkResource)
.asInstanceOf[ScalaKafkaProducer[K, V]]
def close(): Unit = KafkaProducerConnector.defaultHolder.remove(name)(
KafkaProducerConnector.kafkaProducerClosable)
private val mkResource = () => {
val keySer = mkDefaultSerializer[K](ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)
val valueSer = mkDefaultSerializer[V](ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)
new ScalaKafkaProducer[K, V](
new KafkaProducer[K, V](config, keySer.orNull, valueSer.orNull))
}
private def mkDefaultSerializer[A :ClassTag](configKey: String): Option[Serializer[A]] = {
if (!config.containsKey(configKey)) {
implicitly[ClassTag[A]].runtimeClass match {
case c if c == classOf[Array[Byte]] => Some(new ByteArraySerializer().asInstanceOf[Serializer[A]])
case c if c == classOf[String] => Some(new StringSerializer().asInstanceOf[Serializer[A]])
case _ => None
}
} else None
}
}