Search in sources :

Example 1 with KafkaClientFactory

use of org.eclipse.hono.client.kafka.KafkaClientFactory in project hono by eclipse.

the class HonoKafkaConsumer method start.

@Override
public Future<Void> start() {
    context = vertx.getOrCreateContext();
    final Promise<Void> startPromise = Promise.promise();
    runOnContext(v -> {
        // create KafkaConsumer here so that it is created in the Vert.x context of the start() method (KafkaConsumer uses vertx.getOrCreateContext())
        Optional.ofNullable(kafkaConsumerSupplier).map(supplier -> Future.succeededFuture(KafkaConsumer.create(vertx, supplier.get()))).orElseGet(() -> {
            final KafkaClientFactory kafkaClientFactory = new KafkaClientFactory(vertx);
            return kafkaClientFactory.createKafkaConsumerWithRetries(consumerConfig, String.class, Buffer.class, consumerCreationRetriesTimeout);
        }).onFailure(thr -> {
            log.error("error creating consumer [client-id: {}]", getClientId(), thr);
            startPromise.fail(thr);
        }).onSuccess(consumer -> {
            kafkaConsumer = consumer;
            Optional.ofNullable(metricsSupport).ifPresent(ms -> ms.registerKafkaConsumer(kafkaConsumer.unwrap()));
            kafkaConsumer.handler(record -> {
                if (!startPromise.future().isComplete()) {
                    log.debug("postponing record handling until start() is completed [topic: {}, partition: {}, offset: {}]", record.topic(), record.partition(), record.offset());
                }
                startPromise.future().onSuccess(v2 -> {
                    if (respectTtl && KafkaRecordHelper.isTtlElapsed(record.headers())) {
                        onRecordHandlerSkippedForExpiredRecord(record);
                    } else {
                        try {
                            recordHandler.handle(record);
                        } catch (final Exception e) {
                            log.warn("error handling record [topic: {}, partition: {}, offset: {}, headers: {}]", record.topic(), record.partition(), record.offset(), record.headers(), e);
                        }
                    }
                });
            });
            kafkaConsumer.batchHandler(this::onBatchOfRecordsReceived);
            kafkaConsumer.exceptionHandler(error -> log.error("consumer error occurred [client-id: {}]", getClientId(), error));
            installRebalanceListeners();
            // subscribe and wait for rebalance to make sure that when start() completes,
            // the consumer is actually ready to receive records already
            // let polls finish quickly until start() is completed
            kafkaConsumer.asStream().pollTimeout(Duration.ofMillis(10));
            subscribeAndWaitForRebalance().onSuccess(v2 -> {
                kafkaConsumer.asStream().pollTimeout(pollTimeout);
                logSubscribedTopicsOnStartComplete();
            }).onComplete(startPromise);
        });
    });
    return startPromise.future();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Lifecycle(org.eclipse.hono.util.Lifecycle) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RegisterForReflection(io.quarkus.runtime.annotations.RegisterForReflection) KafkaConsumerRecords(io.vertx.kafka.client.consumer.KafkaConsumerRecords) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) KafkaClientFactory(org.eclipse.hono.client.kafka.KafkaClientFactory) Context(io.vertx.core.Context) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) Helper(io.vertx.kafka.client.common.impl.Helper) KafkaClientMetricsSupport(org.eclipse.hono.client.kafka.metrics.KafkaClientMetricsSupport) Duration(java.time.Duration) Map(java.util.Map) Pair(org.eclipse.hono.util.Pair) KafkaReadStreamImpl(io.vertx.kafka.client.consumer.impl.KafkaReadStreamImpl) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) Consumer(org.apache.kafka.clients.consumer.Consumer) Futures(org.eclipse.hono.util.Futures) Logger(org.slf4j.Logger) Collection(java.util.Collection) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Set(java.util.Set) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) UUID(java.util.UUID) KafkaRecordHelper(org.eclipse.hono.client.kafka.KafkaRecordHelper) Field(java.lang.reflect.Field) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) TopicPartition(io.vertx.kafka.client.common.TopicPartition) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) ConsumerRebalanceListener(org.apache.kafka.clients.consumer.ConsumerRebalanceListener) List(java.util.List) Stream(java.util.stream.Stream) Metrics(org.apache.kafka.common.metrics.Metrics) Buffer(io.vertx.core.buffer.Buffer) CooperativeStickyAssignor(org.apache.kafka.clients.consumer.CooperativeStickyAssignor) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) Optional(java.util.Optional) KafkaConsumer(io.vertx.kafka.client.consumer.KafkaConsumer) Pattern(java.util.regex.Pattern) Handler(io.vertx.core.Handler) KafkaClientFactory(org.eclipse.hono.client.kafka.KafkaClientFactory) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Aggregations

RegisterForReflection (io.quarkus.runtime.annotations.RegisterForReflection)1 CompositeFuture (io.vertx.core.CompositeFuture)1 Context (io.vertx.core.Context)1 Future (io.vertx.core.Future)1 Handler (io.vertx.core.Handler)1 Promise (io.vertx.core.Promise)1 Vertx (io.vertx.core.Vertx)1 Buffer (io.vertx.core.buffer.Buffer)1 TopicPartition (io.vertx.kafka.client.common.TopicPartition)1 Helper (io.vertx.kafka.client.common.impl.Helper)1 KafkaConsumer (io.vertx.kafka.client.consumer.KafkaConsumer)1 KafkaConsumerRecord (io.vertx.kafka.client.consumer.KafkaConsumerRecord)1 KafkaConsumerRecords (io.vertx.kafka.client.consumer.KafkaConsumerRecords)1 KafkaReadStreamImpl (io.vertx.kafka.client.consumer.impl.KafkaReadStreamImpl)1 Field (java.lang.reflect.Field)1 HttpURLConnection (java.net.HttpURLConnection)1 Duration (java.time.Duration)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1