Kafka Clients for Kotlin Tests

Utility classes for testing Kafka Clients in Kotlin

License

License

Categories

Categories

Kotlin Languages CLI User Interface
GroupId

GroupId

io.streamthoughts
ArtifactId

ArtifactId

kafka-clients-kotlin-tests
Last Version

Last Version

0.2.0
Release Date

Release Date

Type

Type

jar
Description

Description

Kafka Clients for Kotlin Tests
Utility classes for testing Kafka Clients in Kotlin
Project Organization

Project Organization

streamthoughts

Download kafka-clients-kotlin-tests

How to add to project

<!-- https://jarcasting.com/artifacts/io.streamthoughts/kafka-clients-kotlin-tests/ -->
<dependency>
    <groupId>io.streamthoughts</groupId>
    <artifactId>kafka-clients-kotlin-tests</artifactId>
    <version>0.2.0</version>
</dependency>
// https://jarcasting.com/artifacts/io.streamthoughts/kafka-clients-kotlin-tests/
implementation 'io.streamthoughts:kafka-clients-kotlin-tests:0.2.0'
// https://jarcasting.com/artifacts/io.streamthoughts/kafka-clients-kotlin-tests/
implementation ("io.streamthoughts:kafka-clients-kotlin-tests:0.2.0")
'io.streamthoughts:kafka-clients-kotlin-tests:jar:0.2.0'
<dependency org="io.streamthoughts" name="kafka-clients-kotlin-tests" rev="0.2.0">
  <artifact name="kafka-clients-kotlin-tests" type="jar" />
</dependency>
@Grapes(
@Grab(group='io.streamthoughts', module='kafka-clients-kotlin-tests', version='0.2.0')
)
libraryDependencies += "io.streamthoughts" % "kafka-clients-kotlin-tests" % "0.2.0"
[io.streamthoughts/kafka-clients-kotlin-tests "0.2.0"]

Dependencies

compile (6)

Group / Artifact Type Version
org.jetbrains.kotlin : kotlin-stdlib jar 1.3.72
org.jetbrains.kotlin : kotlin-stdlib-jdk8 jar 1.3.72
org.apache.kafka : kafka_2.13 jar 2.5.0
org.apache.kafka : kafka_2.13 jar 2.5.0
org.apache.kafka : kafka-clients jar 2.5.0
org.apache.curator : curator-test jar 5.1.0

test (3)

Group / Artifact Type Version
org.jetbrains.kotlin : kotlin-test-junit jar 1.3.72
org.junit.platform : junit-platform-launcher jar 1.5.2
org.junit.jupiter : junit-jupiter-engine jar 5.5.2

Project Modules

There are no modules declared in this project.

Kafka Clients for Kotlin

https://github.com/streamthoughts/kafka-clients-kotlin/blob/master/LICENSE GitHub release (latest by date) GitHub issues GitHub Workflow Status GitHub Repo stars

Warning
Be aware that this package is still in heavy development. Some breaking change will occur in future weeks and months. Thank’s for your comprehension.

What is Kafka Clients for Kotlin ?

The Kafka Clients for Kotlin projects packs with convenient Kotlin API for the development of Kafka-based event-driven applications. It provides high-level abstractions both for sending records ProducerContainer and consuming records from topics using one or many concurrent consumers KafkaConsumerWorker.

In addition, it provides builder classes to facilitate the configuration of Producer and Consumer objects: KafkaProducerConfigs and KafkaConsumerConfigs

Kafka Clients for Kotlin is based on the pure java kafka-clients.

How to contribute ?

The project is in its early stages so it can be very easy to contribute by proposing APIs changes, new features and so on. Any feedback, bug reports and PRs are greatly appreciated!

Show your support

You think this project can help you or your team to develop kafka-based application with Kotlin ? Please this repository to support us!

How to give it a try ?

Just add Kafka Clients for Kotlin to the dependencies of your projects.

For Maven

<dependency>
  <groupId>io.streamthoughts</groupId>
  <artifactId>kafka-clients-kotlin</artifactId>
  <version>0.2.0</version>
</dependency>

Getting Started

Writing messages to Kafka

Example: How to create KafkaProducer config ?

val configs = producerConfigsOf()
    .client { bootstrapServers("localhost:9092") }
    .acks(Acks.Leader)
    .keySerializer(StringSerializer::class.java.name)
    .valueSerializer(StringSerializer::class.java.name)

Example with standard KafkaProducer (i.e : using java kafka-clients)

val producer = KafkaProducer<String, String>(configs)

val messages = listOf("I ❤️ Logs", "Making Sense of Stream Processing", "Apache Kafka")
producer.use {
    messages.forEach {value ->
        val record = ProducerRecord<String, String>(topic, value)
        producer.send(record) { m: RecordMetadata, e: Exception? ->
            when (e) {
                null -> println("Record was successfully sent (topic=${m.topic()}, partition=${m.partition()}, offset= ${m.offset()})")
                else -> e.printStackTrace()
            }
        }
    }
}

N.B: See the full source code: ProducerClientExample.kt

Example with Kotlin DSL

val producer: ProducerContainer<String, String> = kafka("localhost:9092") {
    client {
        clientId("my-client")
    }

    producer {
        configure {
            acks(Acks.InSyncReplicas)
        }
        keySerializer(StringSerializer())
        valueSerializer(StringSerializer())

        defaultTopic("demo-topic")

        onSendError {_, _, error ->
            e.printStackTrace()
        }

        onSendSuccess{ _, _, metadata ->
            println("Record was sent successfully: topic=${metadata.topic()}, partition=${metadata.partition()}, offset=${metadata.offset()} ")
        }
    }
}

val messages = listOf("I ❤️ Logs", "Making Sense of Stream Processing", "Apache Kafka")
producer.use {
    producer.init() // create internal producer and call initTransaction() if `transactional.id` is set
    messages.forEach { producer.send(value = it) }
}

N.B: See the full source code: ProducerKotlinDSLExample.kt

Consuming messages from a Kafka topic

Example: How to create KafkaConsumer config ?

val configs = consumerConfigsOf()
    .client { bootstrapServers("localhost:9092") }
    .groupId("demo-consumer-group")
    .keyDeserializer(StringDeserializer::class.java.name)
    .valueDeserializer(StringDeserializer::class.java.name)

Example with standard KafkaConsumer (i.e : using java kafka-clients)

val consumer = KafkaConsumer<String, String>(configs)

consumer.use {
    consumer.subscribe(listOf(topic))
    while(true) {
        consumer
            .poll(Duration.ofMillis(500))
            .forEach { record ->
                println(
                    "Received record with key ${record.key()} " +
                    "and value ${record.value()} from topic ${record.topic()} and partition ${record.partition()}"
                )
            }
    }
}

N.B: See the full source code: ConsumerClientExample.kt

Example with Kotlin DSL

val consumerWorker: ConsumerWorker<String, String> = kafka("localhost:9092") {
    client {
        clientId("my-client")
    }

    val stringDeserializer: Deserializer<String> = StringDeserializer()
    consumer("my-group", stringDeserializer, stringDeserializer) {
        configure {
            maxPollRecords(1000)
            autoOffsetReset(AutoOffsetReset.Earliest)
        }

        onDeserializationError(replaceWithNullOnInvalidRecord())

        onPartitionsAssigned { _: Consumer<*, *>, partitions ->
            println("Partitions assigned: $partitions")
        }

        onPartitionsRevokedAfterCommit { _: Consumer<*, *>, partitions ->
            println("Partitions revoked: $partitions")
        }

        onConsumed { _: Consumer<*, *>, value: String? ->
            println("consumed record-value: $value")
        }

        onConsumedError(closeTaskOnConsumedError())

        Runtime.getRuntime().addShutdownHook(Thread { run { stop() } })
    }
}

consumerWorker.use {
    consumerWorker.start("demo-topic", maxParallelHint = 4)
    runBlocking {
        println("All consumers started, waiting one minute before stopping")
        delay(Duration.ofMinutes(1).toMillis())
    }
}

N.B: See the full source code: ConsumerKotlinDSLExample.kt

How to build project ?

Kafka Clients for Kotlin uses maven-wrapper.

$ ./mvnw clean package

Run Tests

$ ./mvnw clean test

Licence

Copyright 2020 StreamThoughts.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License

io.streamthoughts

StreamThoughts

The leading French start-up in event streaming.

Versions

Version
0.2.0