Skip to content

Instantly share code, notes, and snippets.

@archevel
Created June 24, 2015 02:10
Show Gist options
  • Save archevel/ae30e17a02ae44d3437d to your computer and use it in GitHub Desktop.
Save archevel/ae30e17a02ae44d3437d to your computer and use it in GitHub Desktop.
Intermittently successful
package mykafkatest
import java.net.ServerSocket
import java.nio.file.Files
import java.util.{UUID, Properties}
import kafka.consumer.{Whitelist, ConsumerConfig, Consumer}
import kafka.producer.{ProducerConfig, Producer, KeyedMessage}
import kafka.serializer.StringDecoder
import kafka.server.KafkaConfig
import kafka.server.KafkaServerStartable
import org.apache.curator.test.TestingServer
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
class KafkaSenderTest extends org.scalatest.FunSpecLike with org.scalatest.ShouldMatchers with org.scalatest.BeforeAndAfterAll {
import scala.concurrent.ExecutionContext.Implicits.global
val zkServer = new TestingServer()
val port = new ServerSocket(0).getLocalPort.toString
val tmpDir = Files.createTempDirectory("kafka-test-logs")
val serverProps = new Properties
serverProps.put("broker.id", port)
serverProps.put("log.dirs", tmpDir.toAbsolutePath.toString)
serverProps.put("host.name", "localhost")
serverProps.put("zookeeper.connect", zkServer.getConnectString)
serverProps.put("port", port)
val config = new KafkaConfig(serverProps)
val kafkaServer = new KafkaServerStartable(config)
override def beforeAll ={
kafkaServer.startup()
}
override def afterAll = {
kafkaServer.shutdown()
}
it("should put messages on a kafka queue") {
println("zkServer: " + zkServer.getConnectString)
println("broker port: " + port)
val consumerProps = new Properties()
consumerProps.put("group.id", UUID.randomUUID().toString)
consumerProps.put("zookeeper.connect", zkServer.getConnectString)
val consumerConnector = Consumer.create(new ConsumerConfig(consumerProps))
val topic = "some-topic"
val filterSpec = new Whitelist(topic)
val stream = consumerConnector.createMessageStreamsByFilter(filterSpec, 1, new StringDecoder, new StringDecoder).head
val producerProps = new Properties()
producerProps.put("metadata.broker.list","localhost:"+port)
val sender = new Producer[Array[Byte], Array[Byte]](new ProducerConfig(producerProps))
val keyedMessage = new KeyedMessage[Array[Byte], Array[Byte]]("some-topic", "awesome message".getBytes("UTF-8"))
sender.send(keyedMessage)
val msg = Await.result(Future { stream.take(1) }, 5 seconds)
msg.headOption should not be(empty)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment