|
| 1 | +/* |
| 2 | + * Copyright 2020 StreamThoughts. |
| 3 | + * |
| 4 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 5 | + * contributor license agreements. See the NOTICE file distributed with |
| 6 | + * this work for additional information regarding copyright ownership. |
| 7 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 8 | + * (the "License"); you may not use this file except in compliance with |
| 9 | + * the License. You may obtain a copy of the License at |
| 10 | + * |
| 11 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | + * |
| 13 | + * Unless required by applicable law or agreed to in writing, software |
| 14 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | + * See the License for the specific language governing permissions and |
| 17 | + * limitations under the License. |
| 18 | + */ |
| 19 | +package io.streamthoughts.kafka.client.examples |
| 20 | + |
| 21 | +import io.streamthoughts.kafka.clients.loadProducerConfigs |
| 22 | +import io.streamthoughts.kafka.clients.producer.Acks |
| 23 | +import io.streamthoughts.kafka.clients.producer.KafkaProducerConfigs |
| 24 | +import org.apache.kafka.clients.producer.KafkaProducer |
| 25 | +import org.apache.kafka.clients.producer.ProducerRecord |
| 26 | +import org.apache.kafka.clients.producer.RecordMetadata |
| 27 | +import org.apache.kafka.common.serialization.StringSerializer |
| 28 | +import kotlin.system.exitProcess |
| 29 | + |
| 30 | +fun main(args: Array<String>) { |
| 31 | + |
| 32 | + if (args.size != 2) { |
| 33 | + println("Missing required command line arguments: configFile topic") |
| 34 | + exitProcess(1) |
| 35 | + } |
| 36 | + |
| 37 | + val (config, topic) = args |
| 38 | + |
| 39 | + |
| 40 | + // Load properties from file and customize Producer config. |
| 41 | + val configs: KafkaProducerConfigs = loadProducerConfigs(config) |
| 42 | + .acks(Acks.Leader) |
| 43 | + .keySerializer(StringSerializer::class.java.name) |
| 44 | + .valueSerializer(StringSerializer::class.java.name) |
| 45 | + |
| 46 | + val producer = KafkaProducer<String, String>(configs) |
| 47 | + |
| 48 | + val messages = listOf("I ❤️ Logs", "Making Sense of Stream Processing", "Apache Kafka") |
| 49 | + |
| 50 | + producer.use { |
| 51 | + messages.forEach {value -> |
| 52 | + val record = ProducerRecord<String, String>(topic, value) |
| 53 | + producer.send(record) { m: RecordMetadata, e: Exception? -> |
| 54 | + when (e) { |
| 55 | + null -> println("Record was successfully sent (topic=${m.topic()}, partition=${m.partition()}, offset= ${m.offset()})") |
| 56 | + else -> e.printStackTrace() |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments