/** * Tests that acknowledged offsets are committed using the configured commit interval. */ @Test public void manualAckCommitInterval() { topic = topics.get(1); Duration interval = Duration.ofMillis(500); receiverOptions = receiverOptions .subscription(Collections.singleton(topic)) .commitInterval(interval); AtomicLong lastCommitted = new AtomicLong(-1); final int delayIndex = 5; sendMessages(topic, 0, 20); receiveAndVerify(15, r -> { long offset = r.receiverOffset().offset(); if (r.receiverOffset().offset() < 10) { r.receiverOffset().acknowledge(); if (offset == delayIndex) { TestUtils.sleep(interval.toMillis()); lastCommitted.set(offset); } } else uncommittedMessages.add(r); verifyCommit(r, lastCommitted.get()); return Mono.just(r); }); verifyCommits(groupId, topic, 10); }
public Flux<?> flux() { return KafkaReceiver.create(receiverOptions(Collections.singletonList(topic)).commitInterval(Duration.ZERO)) .receive() .publishOn(scheduler) .concatMap(m -> storeInDB(m.value()) .thenEmpty(m.receiverOffset().commit())) .retry() .doOnCancel(() -> close()); } public Mono<Void> storeInDB(Person person) {
public Disposable consumeMessages(String topic, CountDownLatch latch) { ReceiverOptions<Integer, String> options = receiverOptions.subscription(Collections.singleton(topic)) .addAssignListener(partitions -> log.debug("onPartitionsAssigned {}", partitions)) .addRevokeListener(partitions -> log.debug("onPartitionsRevoked {}", partitions)); Flux<ReceiverRecord<Integer, String>> kafkaFlux = KafkaReceiver.create(options).receive(); return kafkaFlux.subscribe(record -> { ReceiverOffset offset = record.receiverOffset(); System.out.printf("Received message: topic-partition=%s offset=%d timestamp=%s key=%d value=%s\n", offset.topicPartition(), offset.offset(), dateFormat.format(new Date(record.timestamp())), record.key(), record.value()); offset.acknowledge(); latch.countDown(); }); }
private void onCommit(List<ReceiverOffset> offsets, CountDownLatch commitLatch, long[] committedOffsets) { for (ReceiverOffset offset : offsets) { committedOffsets[offset.topicPartition().partition()] = offset.offset() + 1; commitLatch.countDown(); } offsets.clear(); }
public Flux<?> flux() { Scheduler scheduler = Schedulers.newElastic("sample", 60, true); return KafkaReceiver.create(receiverOptions(Collections.singleton(topic)).commitInterval(Duration.ZERO)) .receive() .groupBy(m -> m.receiverOffset().topicPartition()) .flatMap(partitionFlux -> partitionFlux.publishOn(scheduler) .map(r -> processRecord(partitionFlux.key(), r)) .sample(Duration.ofMillis(5000)) .concatMap(offset -> offset.commit())) .doOnCancel(() -> close()); } public ReceiverOffset processRecord(TopicPartition topicPartition, ReceiverRecord<Integer, Person> message) {
public Flux<?> flux() { KafkaSender<Integer, Person> sender = sender(senderOptions()); return KafkaReceiver.create(receiverOptions(Collections.singleton(sourceTopic))) .receive() .map(m -> SenderRecord.create(transform(m.value()), m.receiverOffset())) .as(sender::send) .doOnNext(m -> m.correlationMetadata().acknowledge()) .doOnCancel(() -> close()); } public ProducerRecord<Integer, Person> transform(Person p) {
@Test public void manualCommitBatch() throws Exception { int count = 20; int commitIntervalMessages = 4; CountDownLatch commitLatch = new CountDownLatch(count / commitIntervalMessages); long[] committedOffsets = new long[partitions]; for (int i = 0; i < committedOffsets.length; i++) committedOffsets[i] = -1; List<ReceiverOffset> uncommitted = new ArrayList<>(); receiverOptions = receiverOptions.commitInterval(Duration.ZERO).commitBatchSize(0); KafkaReceiver<Integer, String> receiver = createReceiver(); Flux<? extends ConsumerRecord<Integer, String>> kafkaFlux = receiver.receive() .concatMap(record -> { ReceiverOffset offset = record.receiverOffset(); offset.acknowledge(); uncommitted.add(offset); if (uncommitted.size() == commitIntervalMessages) { return offset.commit() .doOnSuccess(i -> onCommit(uncommitted, commitLatch, committedOffsets)) .doOnError(e -> log.error("Commit exception", e)) .then(Mono.just(record)); } return Mono.just(record); }) .doOnError(e -> log.error("KafkaFlux exception", e)); sendAndWaitForMessages(kafkaFlux, count); checkCommitCallbacks(commitLatch, committedOffsets); }
kafkaFlux.groupBy(m -> m.receiverOffset().topicPartition()) .subscribe(partitionFlux -> subscribeDisposables.add(partitionFlux.publishOn(scheduler).subscribe(record -> { int partition = record.partition(); onReceive(record); latch.countDown(); record.receiverOffset().acknowledge(); inProgressMap.remove(partition); })));
/** * Tests that offsets that are not committed explicitly are not committed * on close and that uncommitted records are redelivered on the next receive. */ @Test public void manualCommitClose() throws Exception { receiverOptions = receiverOptions .commitBatchSize(0) .commitInterval(Duration.ZERO) .subscription(Collections.singletonList(topic)); sendMessages(topic, 0, 20); receiveAndVerify(20, r -> { if (r.receiverOffset().offset() < 5) return r.receiverOffset().commit().then(Mono.just(r)); return Mono.just(r); }); receivedMessages.removeIf(r -> r.offset() >= 5); consumerFactory.addConsumer(new MockConsumer(cluster)); receiveAndVerify(10); }
/** * Tests that assign callbacks are invoked before any records are delivered * when partitions are assigned using group management. */ @Test public void assignCallback() { receiverOptions = receiverOptions.subscription(Collections.singleton(topic)); sendMessages(topic, 0, 10); receiveAndVerify(10, r -> { assertTrue("Assign callback not invoked", assignedPartitions.contains(r.receiverOffset().topicPartition())); return Mono.just(r); }); }
@Test public void publishFromEventScheduler() throws Exception { receiverOptions = receiverOptions .schedulerSupplier(Schedulers::immediate) .addAssignListener(this::onPartitionsAssigned) .subscription(Collections.singletonList(topic)); KafkaReceiver<Integer, String> receiver = KafkaReceiver.create(receiverOptions); AtomicReference<String> publishingThreadName = new AtomicReference<>(); CountDownLatch receiveLatch = new CountDownLatch(1); Disposable disposable = receiver.receive() .doOnNext(record -> { publishingThreadName.set(Thread.currentThread().getName()); record.receiverOffset().acknowledge(); receiveLatch.countDown(); }) .subscribe(); subscribeDisposables.add(disposable); waitFoPartitionAssignment(); sendMessages(0, 1); waitForMessages(receiveLatch); assertNotNull(publishingThreadName.get()); assertTrue(publishingThreadName.get().startsWith("reactive-kafka-")); }
private void verifyCommit(ReceiverRecord<Integer, String> r, long lastCommitted) { TopicPartition partition = r.receiverOffset().topicPartition(); Long committedOffset = cluster.committedOffset(groupId, partition); long offset = r.receiverOffset().offset(); if (lastCommitted >= 0 && offset == lastCommitted) { TestUtils.waitUntil("Offset not committed", null, p -> cluster.committedOffset(groupId, p) == (Long) (offset + 1), partition, Duration.ofSeconds(1)); } committedOffset = cluster.committedOffset(groupId, partition); assertEquals(committedOffset, lastCommitted == -1 ? null : lastCommitted + 1); }
ReceiverOffset offset = assignedPartitions.remove(p); if (offset != null) offset.commit().block(Duration.ofSeconds(receiveTimeoutMillis)); .receive() .doOnNext(m -> { assertTrue(assignedPartitions.containsKey(m.receiverOffset().topicPartition())); assignedPartitions.put(m.receiverOffset().topicPartition(), m.receiverOffset()); receiveLatch.countDown(); })
@Test public void manualCommitFailure() throws Exception { int count = 1; AtomicBoolean commitSuccess = new AtomicBoolean(); Semaphore commitErrorSemaphore = new Semaphore(0); receiverOptions = receiverOptions.commitInterval(Duration.ZERO).commitBatchSize(0); KafkaReceiver<Integer, String> receiver = createReceiver(); Flux<? extends ConsumerRecord<Integer, String>> kafkaFlux = receiver.receive() .doOnNext(record -> { ReceiverOffset offset = record.receiverOffset(); TestableReceiver.setNonExistentPartition(offset); record.receiverOffset().acknowledge(); record.receiverOffset().commit() .doOnError(e -> commitErrorSemaphore.release()) .doOnSuccess(i -> commitSuccess.set(true)) .subscribe(); }) .doOnError(e -> log.error("KafkaFlux exception", e)); subscribe(kafkaFlux, new CountDownLatch(count)); sendMessages(1, count); assertTrue("Commit error callback not invoked", commitErrorSemaphore.tryAcquire(receiveTimeoutMillis, TimeUnit.MILLISECONDS)); assertFalse("Commit of non existent topic succeeded", commitSuccess.get()); }
/** * Send and receive using manual assignment of partitions. */ @Test public void manualAssignment() { receiverOptions = receiverOptions.assignment(cluster.partitions(topic)); sendMessages(topic, 0, 10); receiveAndVerify(10, r -> { assertTrue("Assign callback not invoked", assignedPartitions.contains(r.receiverOffset().topicPartition())); return Mono.just(r); }); }
/** * Tests that acknowledged offsets are committed using the configured batch size. */ @Test public void manualAckCommitBatchSize() { topic = topics.get(1); int batchSize = 4; receiverOptions = receiverOptions .subscription(Collections.singleton(topic)) .commitBatchSize(batchSize); AtomicLong lastCommitted = new AtomicLong(-1); sendMessages(topic, 0, 20); receiveAndVerify(15, r -> { long offset = r.receiverOffset().offset(); if (offset < 10) { r.receiverOffset().acknowledge(); if (((offset + 1) % batchSize) == 0) lastCommitted.set(offset); } else uncommittedMessages.add(r); verifyCommit(r, lastCommitted.get()); return Mono.just(r); }); verifyCommits(groupId, topic, 10); }
/** * Tests that only acknowledged offsets are committed with manual-ack using * {@link KafkaReceiver#receive()}. */ @Test public void manualAck() { receiverOptions = receiverOptions .subscription(Collections.singleton(topic)) .commitBatchSize(1); Map<TopicPartition, Long> acknowledged = new ConcurrentHashMap<>(); for (TopicPartition partition : cluster.partitions(topic)) acknowledged.put(partition, -1L); sendMessages(topic, 0, 20); receiveAndVerify(10, r -> { ReceiverOffset offset = r.receiverOffset(); TopicPartition partition = offset.topicPartition(); Long committedOffset = cluster.committedOffset(groupId, partition); boolean valid = committedOffset == null || acknowledged.get(partition) >= committedOffset - 1; if (offset.offset() % 3 == 0) { offset.acknowledge(); acknowledged.put(partition, offset.offset()); } assertTrue("Unexpected commit state", valid); return Mono.just(r); }); for (Map.Entry<TopicPartition, Long> entry : acknowledged.entrySet()) { Long committedOffset = cluster.committedOffset(groupId, entry.getKey()); assertEquals(entry.getValue() + 1, committedOffset.longValue()); } }
/** * Tests manual commits for {@link KafkaReceiver#receive()} with asynchronous commits. * Tests that commits are completed when the flux is closed gracefully. */ @Test public void manualCommitAsync() throws Exception { int count = 10; CountDownLatch commitLatch = new CountDownLatch(count); receiverOptions = receiverOptions .commitBatchSize(0) .commitInterval(Duration.ofMillis(Long.MAX_VALUE)) .subscription(Collections.singletonList(topic)); sendMessages(topic, 0, count + 10); receiveAndVerify(10, record -> Flux.merge( Mono.just(record), record.receiverOffset() .commit() .doOnSuccess(i -> commitLatch.countDown()) .then(Mono.empty()) ).single()); verifyCommits(groupId, topic, 10); assertTrue("Offsets not committed", commitLatch.await(1, TimeUnit.SECONDS)); }
@Test public void publishFromCustomScheduler() throws Exception { String schedulerName = "custom-scheduler"; Scheduler scheduler = Schedulers.newElastic(schedulerName); receiverOptions = receiverOptions .schedulerSupplier(() -> scheduler) .addAssignListener(this::onPartitionsAssigned) .subscription(Collections.singletonList(topic)); KafkaReceiver<Integer, String> receiver = KafkaReceiver.create(receiverOptions); AtomicReference<String> publishingThreadName = new AtomicReference<>(); CountDownLatch receiveLatch = new CountDownLatch(1); Disposable disposable = receiver.receive() .doOnNext(record -> { publishingThreadName.set(Thread.currentThread().getName()); record.receiverOffset().acknowledge(); receiveLatch.countDown(); }) .subscribe(); subscribeDisposables.add(scheduler); subscribeDisposables.add(disposable); waitFoPartitionAssignment(); sendMessages(0, 1); waitForMessages(receiveLatch); assertNotNull(publishingThreadName.get()); assertTrue(publishingThreadName.get().startsWith(schedulerName)); }
Disposable disposable = new DefaultKafkaReceiver<>(consumerFactory, receiverOptions) .receive() .groupBy(m -> m.receiverOffset().topicPartition()) .subscribe(partitionFlux -> groupDisposables.add(partitionFlux.publishOn(scheduler, 1).subscribe(record -> { int partition = record.partition();