-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
KafkaMessageListenerContainerTests.java
2403 lines (2114 loc) · 92.5 KB
/
KafkaMessageListenerContainerTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016-2019 the original author or authors.
*
* Licensed 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
package org.springframework.kafka.listener;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.event.ConsumerPausedEvent;
import org.springframework.kafka.event.ConsumerResumedEvent;
import org.springframework.kafka.event.ConsumerStoppedEvent;
import org.springframework.kafka.event.ConsumerStoppingEvent;
import org.springframework.kafka.event.NonResponsiveConsumerEvent;
import org.springframework.kafka.listener.ContainerProperties.AckMode;
import org.springframework.kafka.listener.adapter.FilteringMessageListenerAdapter;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.TopicPartitionInitialOffset;
import org.springframework.kafka.support.TopicPartitionInitialOffset.SeekPosition;
import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer2;
import org.springframework.kafka.support.serializer.JsonDeserializer;
import org.springframework.kafka.support.serializer.JsonSerializer;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.rule.EmbeddedKafkaRule;
import org.springframework.kafka.test.utils.ContainerTestUtils;
import org.springframework.kafka.test.utils.KafkaTestUtils;
/**
* Tests for the listener container.
*
* @author Gary Russell
* @author Martin Dam
* @author Artem Bilan
* @author Loic Talhouarne
*/
public class KafkaMessageListenerContainerTests {
private final Log logger = LogFactory.getLog(this.getClass());
private static String topic1 = "testTopic1";
private static String topic2 = "testTopic2";
private static String topic3 = "testTopic3";
private static String topic4 = "testTopic4";
private static String topic5 = "testTopic5";
private static String topic6 = "testTopic6";
private static String topic7 = "testTopic7";
private static String topic8 = "testTopic8";
private static String topic9 = "testTopic9";
private static String topic10 = "testTopic10";
private static String topic11 = "testTopic11";
private static String topic12 = "testTopic12";
private static String topic13 = "testTopic13";
private static String topic14 = "testTopic14";
private static String topic15 = "testTopic15";
private static String topic16 = "testTopic16";
private static String topic17 = "testTopic17";
private static String topic18 = "testTopic18";
private static String topic19 = "testTopic19";
private static String topic20 = "testTopic20";
private static String topic21 = "testTopic21";
@ClassRule
public static EmbeddedKafkaRule embeddedKafkaRule = new EmbeddedKafkaRule(1, true, topic1, topic2, topic3, topic4,
topic5, topic6, topic7, topic8, topic9, topic10, topic11, topic12, topic13, topic14, topic15, topic16,
topic17, topic18, topic19, topic20, topic21);
private static EmbeddedKafkaBroker embeddedKafka = embeddedKafkaRule.getEmbeddedKafka();
@Rule
public TestName testName = new TestName();
@Test
public void testDelegateType() throws Exception {
Map<String, Object> props = KafkaTestUtils.consumerProps("delegate", "false", embeddedKafka);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
ContainerProperties containerProps = new ContainerProperties(topic3);
containerProps.setShutdownTimeout(60_000L);
final AtomicReference<StackTraceElement[]> trace = new AtomicReference<>();
final CountDownLatch latch1 = new CountDownLatch(1);
containerProps.setMessageListener((MessageListener<Integer, String>) record -> {
trace.set(new RuntimeException().getStackTrace());
latch1.countDown();
});
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProps);
container.setBeanName("delegate");
AtomicReference<List<TopicPartitionInitialOffset>> offsets = new AtomicReference<>();
container.setApplicationEventPublisher(e -> {
if (e instanceof ConsumerStoppingEvent) {
ConsumerStoppingEvent event = (ConsumerStoppingEvent) e;
offsets.set(event.getPartitions().stream()
.map(p -> new TopicPartitionInitialOffset(p.topic(), p.partition(),
event.getConsumer().position(p, Duration.ofMillis(10_000))))
.collect(Collectors.toList()));
}
});
assertThat(container.getGroupId()).isEqualTo("delegate");
container.start();
Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
DefaultKafkaProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(topic3);
template.sendDefault(0, 0, "foo");
template.flush();
assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();
// Stack traces are environment dependent - verified in eclipse
// assertThat(trace.get()[1].getMethodName()).contains("invokeRecordListener");
container.stop();
List<TopicPartitionInitialOffset> list = offsets.get();
assertThat(list).isNotNull();
list.forEach(tpio -> {
if (tpio.partition() == 0) {
assertThat(tpio.initialOffset()).isEqualTo(1);
}
else {
assertThat(tpio.initialOffset()).isEqualTo(0);
}
});
final CountDownLatch latch2 = new CountDownLatch(1);
FilteringMessageListenerAdapter<Integer, String> filtering = new FilteringMessageListenerAdapter<>(m -> {
trace.set(new RuntimeException().getStackTrace());
latch2.countDown();
}, d -> false);
filtering = new FilteringMessageListenerAdapter<>(filtering, d -> false); // two levels of nesting
container.getContainerProperties().setMessageListener(filtering);
container.start();
assertThat(KafkaTestUtils.getPropertyValue(container, "listenerConsumer.listenerType"))
.isEqualTo(ListenerType.SIMPLE);
template.sendDefault(0, 0, "foo");
assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue();
// verify that the container called the right method - avoiding the creation of an Acknowledgment
// assertThat(trace.get()[1].getMethodName()).contains("onMessage"); // onMessage(d, a, c) (inner)
// assertThat(trace.get()[2].getMethodName()).contains("onMessage"); // bridge
// assertThat(trace.get()[3].getMethodName()).contains("onMessage"); // onMessage(d, a, c) (outer)
// assertThat(trace.get()[4].getMethodName()).contains("onMessage"); // onMessage(d)
// assertThat(trace.get()[5].getMethodName()).contains("onMessage"); // bridge
// assertThat(trace.get()[6].getMethodName()).contains("invokeRecordListener");
container.stop();
final CountDownLatch latch3 = new CountDownLatch(1);
filtering = new FilteringMessageListenerAdapter<>(
(AcknowledgingConsumerAwareMessageListener<Integer, String>) (d, a, c) -> {
trace.set(new RuntimeException().getStackTrace());
latch3.countDown();
}, d -> false);
container.getContainerProperties().setMessageListener(filtering);
container.start();
assertThat(KafkaTestUtils.getPropertyValue(container, "listenerConsumer.listenerType"))
.isEqualTo(ListenerType.ACKNOWLEDGING_CONSUMER_AWARE);
template.sendDefault(0, 0, "foo");
assertThat(latch3.await(10, TimeUnit.SECONDS)).isTrue();
// verify that the container called the 3 arg method directly
// int i = 0;
// if (trace.get()[1].getClassName().endsWith("AcknowledgingConsumerAwareMessageListener")) {
// // this frame does not appear in eclise, but does in gradle.\
// i++;
// }
// assertThat(trace.get()[i + 1].getMethodName()).contains("onMessage"); // onMessage(d, a, c)
// assertThat(trace.get()[i + 2].getMethodName()).contains("onMessage"); // bridge
// assertThat(trace.get()[i + 3].getMethodName()).contains("invokeRecordListener");
container.stop();
long t = System.currentTimeMillis();
container.stop();
assertThat(System.currentTimeMillis() - t).isLessThan(5000L);
pf.destroy();
}
@Test
public void testNoResetPolicy() throws Exception {
Map<String, Object> props = KafkaTestUtils.consumerProps("delegate", "false", embeddedKafka);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none");
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
ContainerProperties containerProps = new ContainerProperties(topic17);
final AtomicReference<StackTraceElement[]> trace = new AtomicReference<>();
final CountDownLatch latch1 = new CountDownLatch(1);
containerProps.setMessageListener((MessageListener<Integer, String>) record -> {
trace.set(new RuntimeException().getStackTrace());
latch1.countDown();
});
containerProps.setGroupId("delegateGroup");
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProps);
container.setBeanName("delegate");
assertThat(container.getGroupId()).isEqualTo("delegateGroup");
container.start();
int n = 0;
while (n++ < 200 && container.isRunning()) {
Thread.sleep(100);
}
assertThat(container.isRunning()).isFalse();
}
@Test
public void testListenerTypes() throws Exception {
Map<String, Object> props = KafkaTestUtils.consumerProps("lt1", "false", embeddedKafka);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
ContainerProperties containerProps = new ContainerProperties(topic4);
final CountDownLatch latch = new CountDownLatch(8);
final BitSet bits = new BitSet(8);
containerProps.setMessageListener((MessageListener<Integer, String>) m -> {
this.logger.info("lt1");
synchronized (bits) {
bits.set(0);
}
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container1 =
new KafkaMessageListenerContainer<>(cf, containerProps);
container1.setBeanName("lt1");
container1.start();
props.put("group.id", "lt2");
cf = new DefaultKafkaConsumerFactory<>(props);
containerProps.setMessageListener((AcknowledgingMessageListener<Integer, String>) (m, a) -> {
this.logger.info("lt2");
synchronized (bits) {
bits.set(1);
}
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container2 =
new KafkaMessageListenerContainer<>(cf, containerProps);
container2.setBeanName("lt2");
container2.start();
props.put("group.id", "lt3");
cf = new DefaultKafkaConsumerFactory<>(props);
containerProps.setMessageListener((ConsumerAwareMessageListener<Integer, String>) (m, c) -> {
this.logger.info("lt3");
synchronized (bits) {
bits.set(2);
}
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container3 =
new KafkaMessageListenerContainer<>(cf, containerProps);
container3.setBeanName("lt3");
container3.start();
props.put("group.id", "lt4");
cf = new DefaultKafkaConsumerFactory<>(props);
containerProps.setMessageListener((AcknowledgingConsumerAwareMessageListener<Integer, String>) (m, a, c) -> {
this.logger.info("lt4");
synchronized (bits) {
bits.set(3);
}
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container4 =
new KafkaMessageListenerContainer<>(cf, containerProps);
container4.setBeanName("lt4");
container4.start();
props.put("group.id", "lt5");
cf = new DefaultKafkaConsumerFactory<>(props);
containerProps.setMessageListener((BatchMessageListener<Integer, String>) m -> {
this.logger.info("lt5");
synchronized (bits) {
bits.set(4);
}
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container5 =
new KafkaMessageListenerContainer<>(cf, containerProps);
container5.setBeanName("lt5");
container5.start();
props.put("group.id", "lt6");
cf = new DefaultKafkaConsumerFactory<>(props);
containerProps.setMessageListener((BatchAcknowledgingMessageListener<Integer, String>) (m, a) -> {
this.logger.info("lt6");
synchronized (bits) {
bits.set(5);
}
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container6 =
new KafkaMessageListenerContainer<>(cf, containerProps);
container6.setBeanName("lt6");
container6.start();
props.put("group.id", "lt7");
cf = new DefaultKafkaConsumerFactory<>(props);
containerProps.setMessageListener((BatchConsumerAwareMessageListener<Integer, String>) (m, c) -> {
this.logger.info("lt7");
synchronized (bits) {
bits.set(6);
}
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container7 =
new KafkaMessageListenerContainer<>(cf, containerProps);
container7.setBeanName("lt7");
container7.start();
props.put("group.id", "lt8");
cf = new DefaultKafkaConsumerFactory<>(props);
containerProps
.setMessageListener((BatchAcknowledgingConsumerAwareMessageListener<Integer, String>) (m, a, c) -> {
this.logger.info("lt8");
synchronized (bits) {
bits.set(7);
}
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container8 =
new KafkaMessageListenerContainer<>(cf, containerProps);
container8.setBeanName("lt8");
container8.start();
Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
DefaultKafkaProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(topic4);
template.sendDefault(0, 0, "foo");
template.flush();
pf.destroy();
assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();
assertThat(bits.cardinality()).isEqualTo(8);
container1.stop();
container2.stop();
container3.stop();
container4.stop();
container5.stop();
container6.stop();
container7.stop();
container8.stop();
}
@Test
public void testCommitsAreFlushedOnStop() throws Exception {
Map<String, Object> props = KafkaTestUtils.consumerProps("flushedOnStop", "false", embeddedKafka);
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
ContainerProperties containerProps = new ContainerProperties(topic5);
containerProps.setAckCount(1);
// set large values, ensuring that commits don't happen before `stop()`
containerProps.setAckTime(20000);
containerProps.setAckCount(20000);
containerProps.setAckMode(AckMode.COUNT_TIME);
final CountDownLatch latch = new CountDownLatch(4);
containerProps.setMessageListener((MessageListener<Integer, String>) message -> {
logger.info("flushed: " + message);
latch.countDown();
});
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProps);
container.setBeanName("testManualFlushed");
container.start();
Consumer<?, ?> consumer = spyOnConsumer(container);
ContainerTestUtils.waitForAssignment(container, embeddedKafka.getPartitionsPerTopic());
Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
ProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(topic5);
template.sendDefault(0, 0, "foo");
template.sendDefault(1, 2, "bar");
template.flush();
Thread.sleep(300);
template.sendDefault(0, 0, "fiz");
template.sendDefault(1, 2, "buz");
template.flush();
// Verify that commitSync is called when paused
assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
// Verify that just the initial commit is processed before stop
verify(consumer, times(1)).commitSync(anyMap());
container.stop();
// Verify that a commit has been made on stop
verify(consumer, times(2)).commitSync(anyMap());
}
@Test
public void testRecordAck() throws Exception {
logger.info("Start record ack");
Map<String, Object> props = KafkaTestUtils.consumerProps("test6", "false", embeddedKafka);
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
ContainerProperties containerProps = new ContainerProperties(topic6);
containerProps.setMessageListener((MessageListener<Integer, String>) message -> {
logger.info("record ack: " + message);
});
containerProps.setSyncCommits(true);
containerProps.setAckMode(AckMode.RECORD);
containerProps.setAckOnError(false);
// containerProps.setCommitLogLevel(LogIfLevelEnabled.Level.WARN);
CountDownLatch stubbingComplete = new CountDownLatch(1);
KafkaMessageListenerContainer<Integer, String> container = spyOnContainer(
new KafkaMessageListenerContainer<>(cf, containerProps), stubbingComplete);
container.setBeanName("testRecordAcks");
container.start();
Consumer<?, ?> containerConsumer = spyOnConsumer(container);
final CountDownLatch latch = new CountDownLatch(2);
willAnswer(invocation -> {
Map<TopicPartition, OffsetAndMetadata> map = invocation.getArgument(0);
try {
return invocation.callRealMethod();
}
finally {
for (Entry<TopicPartition, OffsetAndMetadata> entry : map.entrySet()) {
if (entry.getValue().offset() == 2) {
latch.countDown();
}
}
}
}).given(containerConsumer)
.commitSync(anyMap());
stubbingComplete.countDown();
ContainerTestUtils.waitForAssignment(container, embeddedKafka.getPartitionsPerTopic());
Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
ProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(topic6);
template.sendDefault(0, 0, "foo");
template.sendDefault(1, 0, "bar");
template.sendDefault(0, 0, "baz");
template.sendDefault(1, 0, "qux");
template.flush();
assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
Consumer<Integer, String> consumer = cf.createConsumer();
consumer.assign(Arrays.asList(new TopicPartition(topic6, 0), new TopicPartition(topic6, 1)));
assertThat(consumer.position(new TopicPartition(topic6, 0))).isEqualTo(2);
assertThat(consumer.position(new TopicPartition(topic6, 1))).isEqualTo(2);
container.stop();
consumer.close();
logger.info("Stop record ack");
}
@SuppressWarnings("unchecked")
@Test
public void testRecordAckMock() throws Exception {
ConsumerFactory<Integer, String> cf = mock(ConsumerFactory.class);
Consumer<Integer, String> consumer = mock(Consumer.class);
given(cf.createConsumer(eq("grp"), eq("clientId"), isNull(), isNull())).willReturn(consumer);
final Map<TopicPartition, List<ConsumerRecord<Integer, String>>> records = new HashMap<>();
records.put(new TopicPartition("foo", 0), Arrays.asList(
new ConsumerRecord<>("foo", 0, 0L, 1, "foo"),
new ConsumerRecord<>("foo", 0, 1L, 1, "bar")));
ConsumerRecords<Integer, String> consumerRecords = new ConsumerRecords<>(records);
given(consumer.poll(any(Duration.class))).willAnswer(i -> {
Thread.sleep(50);
return consumerRecords;
});
TopicPartitionInitialOffset[] topicPartition = new TopicPartitionInitialOffset[] {
new TopicPartitionInitialOffset("foo", 0) };
ContainerProperties containerProps = new ContainerProperties(topicPartition);
containerProps.setGroupId("grp");
containerProps.setAckMode(AckMode.RECORD);
final CountDownLatch latch = new CountDownLatch(2);
MessageListener<Integer, String> messageListener = spy(
new MessageListener<Integer, String>() { // Cannot be lambda: Mockito doesn't mock final classes
@Override
public void onMessage(ConsumerRecord<Integer, String> data) {
latch.countDown();
if (latch.getCount() == 0) {
records.clear();
}
}
});
final CountDownLatch commitLatch = new CountDownLatch(2);
willAnswer(i -> {
commitLatch.countDown();
return null;
}
).given(consumer).commitSync(any(Map.class));
containerProps.setMessageListener(messageListener);
containerProps.setClientId("clientId");
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProps);
container.start();
assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(commitLatch.await(10, TimeUnit.SECONDS)).isTrue();
InOrder inOrder = inOrder(messageListener, consumer);
inOrder.verify(consumer).poll(Duration.ofMillis(ContainerProperties.DEFAULT_POLL_TIMEOUT));
inOrder.verify(messageListener).onMessage(any(ConsumerRecord.class));
inOrder.verify(consumer).commitSync(any(Map.class));
inOrder.verify(messageListener).onMessage(any(ConsumerRecord.class));
inOrder.verify(consumer).commitSync(any(Map.class));
container.stop();
verify(consumer).wakeup();
}
@SuppressWarnings("unchecked")
@Test
public void testRecordAckAfterStop() throws Exception {
ConsumerFactory<Integer, String> cf = mock(ConsumerFactory.class);
Consumer<Integer, String> consumer = mock(Consumer.class);
given(cf.createConsumer(eq("grp"), eq("clientId"), isNull(), any())).willReturn(consumer);
final Map<TopicPartition, List<ConsumerRecord<Integer, String>>> records = new HashMap<>();
records.put(new TopicPartition("foo", 0), Collections.singletonList(
new ConsumerRecord<>("foo", 0, 0L, 1, "foo")));
ConsumerRecords<Integer, String> consumerRecords = new ConsumerRecords<>(records);
given(consumer.poll(any(Duration.class))).willAnswer(i -> {
Thread.sleep(50);
return consumerRecords;
});
TopicPartitionInitialOffset[] topicPartition = new TopicPartitionInitialOffset[] {
new TopicPartitionInitialOffset("foo", 0) };
ContainerProperties containerProps = new ContainerProperties(topicPartition);
containerProps.setGroupId("grp");
containerProps.setAckMode(AckMode.RECORD);
containerProps.setMissingTopicsFatal(false);
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
MessageListener<Integer, String> messageListener = spy(
new MessageListener<Integer, String>() { // Cannot be lambda: Mockito doesn't mock final classes
@Override
public void onMessage(ConsumerRecord<Integer, String> data) {
latch1.countDown();
try {
latch2.await(10, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
final CountDownLatch commitLatch = new CountDownLatch(1);
willAnswer(i -> {
commitLatch.countDown();
return null;
}
).given(consumer).commitSync(anyMap());
containerProps.setMessageListener(messageListener);
containerProps.setClientId("clientId");
containerProps.setShutdownTimeout(5L);
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProps);
container.start();
assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();
container.stop();
latch2.countDown();
assertThat(commitLatch.await(10, TimeUnit.SECONDS)).isTrue();
InOrder inOrder = inOrder(messageListener, consumer);
inOrder.verify(consumer).poll(Duration.ofMillis(ContainerProperties.DEFAULT_POLL_TIMEOUT));
inOrder.verify(messageListener).onMessage(any(ConsumerRecord.class));
inOrder.verify(consumer).commitSync(anyMap());
verify(consumer, never()).wakeup();
}
@Test
public void testRecordAckMockForeignThread() throws Exception {
testRecordAckMockForeignThreadGuts(AckMode.MANUAL);
}
@Test
public void testRecordAckMockForeignThreadImmediate() throws Exception {
testRecordAckMockForeignThreadGuts(AckMode.MANUAL_IMMEDIATE);
}
@SuppressWarnings("unchecked")
private void testRecordAckMockForeignThreadGuts(AckMode ackMode) throws Exception {
ConsumerFactory<Integer, String> cf = mock(ConsumerFactory.class);
Consumer<Integer, String> consumer = mock(Consumer.class);
given(cf.createConsumer(eq("grp"), eq("clientId"), isNull(), isNull())).willReturn(consumer);
final Map<TopicPartition, List<ConsumerRecord<Integer, String>>> records = new HashMap<>();
records.put(new TopicPartition("foo", 0), Arrays.asList(
new ConsumerRecord<>("foo", 0, 0L, 1, "foo"),
new ConsumerRecord<>("foo", 0, 1L, 1, "bar")));
ConsumerRecords<Integer, String> consumerRecords = new ConsumerRecords<>(records);
long sleepFor = ackMode.equals(AckMode.MANUAL_IMMEDIATE) ? 20_000 : 50;
AtomicBoolean first = new AtomicBoolean(true);
given(consumer.poll(any(Duration.class))).willAnswer(i -> {
if (!first.getAndSet(false)) {
try {
Thread.sleep(sleepFor);
}
catch (@SuppressWarnings("unused") InterruptedException ex) {
throw new WakeupException();
}
}
return consumerRecords;
});
TopicPartitionInitialOffset[] topicPartition = new TopicPartitionInitialOffset[] {
new TopicPartitionInitialOffset("foo", 0) };
ContainerProperties containerProps = new ContainerProperties(topicPartition);
containerProps.setGroupId("grp");
containerProps.setAckMode(ackMode);
containerProps.setMissingTopicsFatal(false);
final CountDownLatch latch = new CountDownLatch(2);
final List<Acknowledgment> acks = new ArrayList<>();
final AtomicReference<Thread> consumerThread = new AtomicReference<>();
AcknowledgingMessageListener<Integer, String> messageListener = spy(
new AcknowledgingMessageListener<Integer, String>() { // Mockito doesn't mock final classes
@Override
public void onMessage(ConsumerRecord<Integer, String> data, Acknowledgment acknowledgment) {
acks.add(acknowledgment);
consumerThread.set(Thread.currentThread());
latch.countDown();
if (latch.getCount() == 0) {
records.clear();
}
}
});
willAnswer(inv -> {
consumerThread.get().interrupt();
return null;
}).given(consumer).wakeup();
final CountDownLatch commitLatch = new CountDownLatch(1);
final AtomicReference<Thread> commitThread = new AtomicReference<>();
willAnswer(i -> {
commitThread.set(Thread.currentThread());
commitLatch.countDown();
return null;
}
).given(consumer).commitSync(any(Map.class));
containerProps.setMessageListener(messageListener);
containerProps.setClientId("clientId");
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProps);
container.start();
assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
long t1 = System.currentTimeMillis();
acks.get(1).acknowledge();
assertThat(commitLatch.await(10, TimeUnit.SECONDS)).isTrue();
InOrder inOrder = inOrder(messageListener, consumer);
inOrder.verify(consumer).poll(Duration.ofMillis(ContainerProperties.DEFAULT_POLL_TIMEOUT));
inOrder.verify(messageListener, times(2)).onMessage(any(ConsumerRecord.class), any(Acknowledgment.class));
inOrder.verify(consumer).commitSync(any(Map.class));
container.stop();
assertThat(commitThread.get()).isSameAs(consumerThread.get());
assertThat(System.currentTimeMillis() - t1).isLessThan(15_000);
}
@SuppressWarnings("unchecked")
@Test
public void testNonResponsiveConsumerEvent() throws Exception {
ConsumerFactory<Integer, String> cf = mock(ConsumerFactory.class);
Consumer<Integer, String> consumer = mock(Consumer.class);
given(cf.createConsumer(eq("grp"), eq(""), isNull(), isNull())).willReturn(consumer);
final Map<TopicPartition, List<ConsumerRecord<Integer, String>>> records = new HashMap<>();
records.put(new TopicPartition("foo", 0), Arrays.asList(
new ConsumerRecord<>("foo", 0, 0L, 1, "foo"),
new ConsumerRecord<>("foo", 0, 1L, 1, "bar")));
final CountDownLatch deadLatch = new CountDownLatch(1);
given(consumer.poll(any(Duration.class))).willAnswer(i -> {
deadLatch.await(10, TimeUnit.SECONDS);
throw new WakeupException();
});
willAnswer(i -> {
deadLatch.countDown();
return null;
}).given(consumer).wakeup();
TopicPartitionInitialOffset[] topicPartition = new TopicPartitionInitialOffset[] {
new TopicPartitionInitialOffset("foo", 0) };
ContainerProperties containerProps = new ContainerProperties(topicPartition);
containerProps.setGroupId("grp");
containerProps.setNoPollThreshold(2.0f);
containerProps.setPollTimeout(10);
containerProps.setMonitorInterval(1);
containerProps.setMessageListener(mock(MessageListener.class));
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProps);
final CountDownLatch latch = new CountDownLatch(1);
container.setApplicationEventPublisher(e -> {
if (e instanceof NonResponsiveConsumerEvent) {
latch.countDown();
}
});
container.start();
assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
container.stop();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testNonResponsiveConsumerEventNotIssuedWithActiveConsumer() throws Exception {
ConsumerFactory<Integer, String> cf = mock(ConsumerFactory.class);
Consumer<Integer, String> consumer = mock(Consumer.class);
given(cf.createConsumer(isNull(), eq(""), isNull(), isNull())).willReturn(consumer);
ConsumerRecords records = new ConsumerRecords(Collections.emptyMap());
CountDownLatch latch = new CountDownLatch(20);
given(consumer.poll(any(Duration.class))).willAnswer(i -> {
Thread.sleep(100);
latch.countDown();
return records;
});
TopicPartitionInitialOffset[] topicPartition = new TopicPartitionInitialOffset[] {
new TopicPartitionInitialOffset("foo", 0) };
ContainerProperties containerProps = new ContainerProperties(topicPartition);
containerProps.setNoPollThreshold(2.0f);
containerProps.setPollTimeout(100);
containerProps.setMonitorInterval(1);
containerProps.setMessageListener(mock(MessageListener.class));
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProps);
final AtomicInteger eventCounter = new AtomicInteger();
container.setApplicationEventPublisher(e -> {
if (e instanceof NonResponsiveConsumerEvent) {
eventCounter.incrementAndGet();
}
});
container.start();
assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
container.stop();
assertThat(eventCounter.get()).isEqualTo(0);
}
@Test
public void testBatchAck() throws Exception {
logger.info("Start batch ack");
Map<String, Object> props = KafkaTestUtils.consumerProps("test6", "false", embeddedKafka);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
ContainerProperties containerProps = new ContainerProperties(topic7);
containerProps.setMessageListener((MessageListener<Integer, String>) message -> {
logger.info("batch ack: " + message);
});
containerProps.setSyncCommits(true);
containerProps.setAckMode(AckMode.BATCH);
containerProps.setPollTimeout(100);
containerProps.setAckOnError(false);
CountDownLatch stubbingComplete = new CountDownLatch(1);
KafkaMessageListenerContainer<Integer, String> container = spyOnContainer(
new KafkaMessageListenerContainer<>(cf, containerProps), stubbingComplete);
container.setBeanName("testBatchAcks");
container.start();
Consumer<?, ?> containerConsumer = spyOnConsumer(container);
final CountDownLatch firstBatchLatch = new CountDownLatch(1);
final CountDownLatch latch = new CountDownLatch(2);
willAnswer(invocation -> {
Map<TopicPartition, OffsetAndMetadata> map = invocation.getArgument(0);
for (Entry<TopicPartition, OffsetAndMetadata> entry : map.entrySet()) {
if (entry.getValue().offset() == 2) {
firstBatchLatch.countDown();
}
}
try {
return invocation.callRealMethod();
}
finally {
for (Entry<TopicPartition, OffsetAndMetadata> entry : map.entrySet()) {
if (entry.getValue().offset() == 2) {
latch.countDown();
}
}
}
}).given(containerConsumer)
.commitSync(anyMap());
stubbingComplete.countDown();
Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
ProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(topic7);
template.sendDefault(0, 0, "foo");
template.sendDefault(0, 0, "baz");
template.sendDefault(1, 0, "bar");
template.sendDefault(1, 0, "qux");
template.flush();
assertThat(firstBatchLatch.await(9, TimeUnit.SECONDS)).isTrue();
assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
Consumer<Integer, String> consumer = cf.createConsumer();
consumer.assign(Arrays.asList(new TopicPartition(topic7, 0), new TopicPartition(topic7, 1)));
assertThat(consumer.position(new TopicPartition(topic7, 0))).isEqualTo(2);
assertThat(consumer.position(new TopicPartition(topic7, 1))).isEqualTo(2);
container.stop();
consumer.close();
logger.info("Stop batch ack");
}
@Test
public void testBatchListener() throws Exception {
logger.info("Start batch listener");
Map<String, Object> props = KafkaTestUtils.consumerProps("test8", "false", embeddedKafka);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
ContainerProperties containerProps = new ContainerProperties(topic8);
containerProps.setMessageListener((BatchMessageListener<Integer, String>) messages -> {
logger.info("batch listener: " + messages);
});
containerProps.setSyncCommits(true);
containerProps.setAckMode(AckMode.BATCH);
containerProps.setPollTimeout(100);
containerProps.setAckOnError(false);
CountDownLatch stubbingComplete = new CountDownLatch(1);
KafkaMessageListenerContainer<Integer, String> container = spyOnContainer(
new KafkaMessageListenerContainer<>(cf, containerProps), stubbingComplete);
container.setBeanName("testBatchListener");
container.start();
Consumer<?, ?> containerConsumer = spyOnConsumer(container);
final CountDownLatch firstBatchLatch = new CountDownLatch(1);
final CountDownLatch latch = new CountDownLatch(2);
willAnswer(invocation -> {
Map<TopicPartition, OffsetAndMetadata> map = invocation.getArgument(0);
for (Entry<TopicPartition, OffsetAndMetadata> entry : map.entrySet()) {
if (entry.getValue().offset() == 2) {
firstBatchLatch.countDown();
}
}
try {
return invocation.callRealMethod();
}
finally {
for (Entry<TopicPartition, OffsetAndMetadata> entry : map.entrySet()) {
if (entry.getValue().offset() == 2) {
latch.countDown();
}
}
}
}).given(containerConsumer)
.commitSync(anyMap());
stubbingComplete.countDown();
Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
ProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(topic8);
template.sendDefault(0, 0, "foo");
template.sendDefault(0, 0, "baz");
template.sendDefault(1, 0, "bar");
template.sendDefault(1, 0, "qux");
template.flush();
assertThat(firstBatchLatch.await(9, TimeUnit.SECONDS)).isTrue();
assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
Consumer<Integer, String> consumer = cf.createConsumer();
consumer.assign(Arrays.asList(new TopicPartition(topic8, 0), new TopicPartition(topic8, 1)));
assertThat(consumer.position(new TopicPartition(topic8, 0))).isEqualTo(2);
assertThat(consumer.position(new TopicPartition(topic8, 1))).isEqualTo(2);
container.stop();
consumer.close();
logger.info("Stop batch listener");
}
@Test
public void testBatchListenerManual() throws Exception {
logger.info("Start batch listener manual");
Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
ProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(topic9);
template.sendDefault(0, 0, "foo");
template.sendDefault(0, 0, "baz");
template.sendDefault(1, 0, "bar");
template.sendDefault(1, 0, "qux");
template.flush();
Map<String, Object> props = KafkaTestUtils.consumerProps("test9", "false", embeddedKafka);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
ContainerProperties containerProps = new ContainerProperties(topic9);
final CountDownLatch latch = new CountDownLatch(4);
containerProps.setMessageListener((BatchAcknowledgingMessageListener<Integer, String>) (messages, ack) -> {
logger.info("batch listener manual: " + messages);
for (int i = 0; i < messages.size(); i++) {
latch.countDown();
}
ack.acknowledge();
});
containerProps.setSyncCommits(true);
containerProps.setAckMode(AckMode.MANUAL_IMMEDIATE);
containerProps.setPollTimeout(100);
containerProps.setAckOnError(false);
CountDownLatch stubbingComplete = new CountDownLatch(1);
KafkaMessageListenerContainer<Integer, String> container = spyOnContainer(
new KafkaMessageListenerContainer<>(cf, containerProps), stubbingComplete);
container.setBeanName("testBatchListenerManual");
container.start();
Consumer<?, ?> containerConsumer = spyOnConsumer(container);
final CountDownLatch commitLatch = new CountDownLatch(2);
AtomicBoolean smallOffsetCommitted = new AtomicBoolean(false);
willAnswer(invocation -> {
Map<TopicPartition, OffsetAndMetadata> map = invocation.getArgument(0);
try {
return invocation.callRealMethod();
}
finally {