-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
ReplyingKafkaTemplate.java
507 lines (444 loc) · 17.3 KB
/
ReplyingKafkaTemplate.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
/*
* Copyright 2018-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.requestreply;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.log.LogAccessor;
import org.springframework.kafka.KafkaException;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.listener.BatchMessageListener;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.listener.GenericMessageListenerContainer;
import org.springframework.kafka.listener.ListenerUtils;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.support.TopicPartitionOffset;
import org.springframework.kafka.support.serializer.DeserializationException;
import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer2;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.Assert;
/**
* A KafkaTemplate that implements request/reply semantics.
*
* @param <K> the key type.
* @param <V> the outbound data type.
* @param <R> the reply data type.
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.1.3
*
*/
public class ReplyingKafkaTemplate<K, V, R> extends KafkaTemplate<K, V> implements BatchMessageListener<K, R>,
InitializingBean, SmartLifecycle, DisposableBean, ReplyingKafkaOperations<K, V, R> {
private static final String WITH_CORRELATION_ID = " with correlationId: ";
private static final int FIVE = 5;
private static final Duration DEFAULT_REPLY_TIMEOUT = Duration.ofSeconds(FIVE);
private final GenericMessageListenerContainer<K, R> replyContainer;
private final ConcurrentMap<CorrelationKey, RequestReplyFuture<K, V, R>> futures = new ConcurrentHashMap<>();
private final byte[] replyTopic;
private final byte[] replyPartition;
private TaskScheduler scheduler = new ThreadPoolTaskScheduler();
private int phase;
private boolean autoStartup = true;
private Duration defaultReplyTimeout = DEFAULT_REPLY_TIMEOUT;
private boolean schedulerSet;
private boolean sharedReplyTopic;
private Function<ProducerRecord<K, V>, CorrelationKey> correlationStrategy = ReplyingKafkaTemplate::defaultCorrelationIdStrategy;
private String correlationHeaderName = KafkaHeaders.CORRELATION_ID;
private String replyTopicHeaderName = KafkaHeaders.REPLY_TOPIC;
private String replyPartitionHeaderName = KafkaHeaders.REPLY_PARTITION;
private volatile boolean running;
private volatile boolean schedulerInitialized;
public ReplyingKafkaTemplate(ProducerFactory<K, V> producerFactory,
GenericMessageListenerContainer<K, R> replyContainer) {
this(producerFactory, replyContainer, false);
}
public ReplyingKafkaTemplate(ProducerFactory<K, V> producerFactory,
GenericMessageListenerContainer<K, R> replyContainer, boolean autoFlush) {
super(producerFactory, autoFlush);
Assert.notNull(replyContainer, "'replyContainer' cannot be null");
this.replyContainer = replyContainer;
this.replyContainer.setupMessageListener(this);
ContainerProperties properties = this.replyContainer.getContainerProperties();
String tempReplyTopic = null;
byte[] tempReplyPartition = null;
TopicPartitionOffset[] topicPartitionsToAssign = properties.getTopicPartitionsToAssign();
String[] topics = properties.getTopics();
if (topics != null && topics.length == 1) {
tempReplyTopic = topics[0];
}
else if (topicPartitionsToAssign != null && topicPartitionsToAssign.length == 1) {
TopicPartitionOffset topicPartitionOffset = topicPartitionsToAssign[0];
Assert.notNull(topicPartitionOffset, "'topicPartitionsToAssign' must not be null");
tempReplyTopic = topicPartitionOffset.getTopic();
ByteBuffer buffer = ByteBuffer.allocate(4); // NOSONAR magic #
buffer.putInt(topicPartitionOffset.getPartition());
tempReplyPartition = buffer.array();
}
if (tempReplyTopic == null) {
this.replyTopic = null;
this.replyPartition = null;
this.logger.debug(() -> "Could not determine container's reply topic/partition; senders must populate "
+ "at least the " + KafkaHeaders.REPLY_TOPIC + " header, and optionally the "
+ KafkaHeaders.REPLY_PARTITION + " header");
}
else {
this.replyTopic = tempReplyTopic.getBytes(StandardCharsets.UTF_8);
this.replyPartition = tempReplyPartition;
}
}
public void setTaskScheduler(TaskScheduler scheduler) {
Assert.notNull(scheduler, "'scheduler' cannot be null");
this.scheduler = scheduler;
this.schedulerSet = true;
}
/**
* Return the reply timeout used if no replyTimeout is provided in the
* {@link #sendAndReceive(ProducerRecord, Duration)} call.
* @return the timeout.
* @deprecated in favor of {@link #getDefaultReplyTimeout()}.
*/
@Deprecated
protected long getReplyTimeout() {
return this.defaultReplyTimeout.toMillis();
}
/**
* Set the reply timeout used if no replyTimeout is provided in the
* {@link #sendAndReceive(ProducerRecord, Duration)} call.
* @param replyTimeout the timeout.
* @deprecated in favor of {@link #setDefaultReplyTimeout(Duration)}.
*/
@Deprecated
public void setReplyTimeout(long replyTimeout) {
Assert.isTrue(replyTimeout >= 0, "'replyTimeout' must be >= 0");
this.defaultReplyTimeout = Duration.ofMillis(replyTimeout);
}
/**
* Return the reply timeout used if no replyTimeout is provided in the
* {@link #sendAndReceive(ProducerRecord, Duration)} call.
* @return the timeout.
* @since 2.3
*/
protected Duration getDefaultReplyTimeout() {
return this.defaultReplyTimeout;
}
/**
* Set the reply timeout used if no replyTimeout is provided in the
* {@link #sendAndReceive(ProducerRecord, Duration)} call.
* @param defaultReplyTimeout the timeout.
* @since 2.3
*/
public void setDefaultReplyTimeout(Duration defaultReplyTimeout) {
Assert.notNull(defaultReplyTimeout, "'defaultReplyTimeout' cannot be null");
Assert.isTrue(defaultReplyTimeout.toMillis() >= 0, "'replyTimeout' must be >= 0");
this.defaultReplyTimeout = defaultReplyTimeout;
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public int getPhase() {
return this.phase;
}
public void setPhase(int phase) {
this.phase = phase;
}
@Override
public boolean isAutoStartup() {
return this.autoStartup;
}
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
/**
* Return the topics/partitions assigned to the replying listener container.
* @return the topics/partitions.
*/
public Collection<TopicPartition> getAssignedReplyTopicPartitions() {
return this.replyContainer.getAssignedPartitions();
}
/**
* Set to true when multiple templates are using the same topic for replies. This
* simply changes logs for unexpected replies to debug instead of error.
* @param sharedReplyTopic true if using a shared topic.
* @since 2.2
*/
public void setSharedReplyTopic(boolean sharedReplyTopic) {
this.sharedReplyTopic = sharedReplyTopic;
}
/**
* Set a function to be called to establish a unique correlation key for each request
* record.
* @param correlationStrategy the function.
* @since 2.3
*/
public void setCorrelationIdStrategy(Function<ProducerRecord<K, V>, CorrelationKey> correlationStrategy) {
Assert.notNull(correlationStrategy, "'correlationStrategy' cannot be null");
this.correlationStrategy = correlationStrategy;
}
/**
* Set a custom header name for the correlation id. Default
* {@link KafkaHeaders#CORRELATION_ID}.
* @param correlationHeaderName the header name.
* @since 2.3
*/
public void setCorrelationHeaderName(String correlationHeaderName) {
Assert.notNull(correlationHeaderName, "'correlationHeaderName' cannot be null");
this.correlationHeaderName = correlationHeaderName;
}
/**
* Set a custom header name for the reply topic. Default
* {@link KafkaHeaders#REPLY_TOPIC}.
* @param replyTopicHeaderName the header name.
* @since 2.3
*/
public void setReplyTopicHeaderName(String replyTopicHeaderName) {
Assert.notNull(replyTopicHeaderName, "'replyTopicHeaderName' cannot be null");
this.replyTopicHeaderName = replyTopicHeaderName;
}
/**
* Set a custom header name for the reply partition. Default
* {@link KafkaHeaders#REPLY_PARTITION}.
* @param replyPartitionHeaderName the reply partition header name.
* @since 2.3
*/
public void setReplyPartitionHeaderName(String replyPartitionHeaderName) {
Assert.notNull(replyPartitionHeaderName, "'replyPartitionHeaderName' cannot be null");
this.replyPartitionHeaderName = replyPartitionHeaderName;
}
@Override
public void afterPropertiesSet() {
if (!this.schedulerSet && !this.schedulerInitialized) {
((ThreadPoolTaskScheduler) this.scheduler).initialize();
this.schedulerInitialized = true;
}
}
@Override
public synchronized void start() {
if (!this.running) {
try {
afterPropertiesSet();
}
catch (Exception e) {
throw new KafkaException("Failed to initialize", e);
}
this.replyContainer.start();
this.running = true;
}
}
@Override
public synchronized void stop() {
if (this.running) {
this.running = false;
this.replyContainer.stop();
this.futures.clear();
}
}
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
@Override
public RequestReplyFuture<K, V, R> sendAndReceive(ProducerRecord<K, V> record) {
return sendAndReceive(record, null);
}
@Override
public RequestReplyFuture<K, V, R> sendAndReceive(ProducerRecord<K, V> record, @Nullable Duration replyTimeout) {
Assert.state(this.running, "Template has not been start()ed"); // NOSONAR (sync)
CorrelationKey correlationId = this.correlationStrategy.apply(record);
Assert.notNull(correlationId, "the created 'correlationId' cannot be null");
Headers headers = record.headers();
boolean hasReplyTopic = headers.lastHeader(KafkaHeaders.REPLY_TOPIC) != null;
if (!hasReplyTopic && this.replyTopic != null) {
headers.add(new RecordHeader(this.replyTopicHeaderName, this.replyTopic));
if (this.replyPartition != null) {
headers.add(new RecordHeader(this.replyPartitionHeaderName, this.replyPartition));
}
}
headers.add(new RecordHeader(this.correlationHeaderName, correlationId.getCorrelationId()));
this.logger.debug(() -> "Sending: " + record + WITH_CORRELATION_ID + correlationId);
RequestReplyFuture<K, V, R> future = new RequestReplyFuture<>();
this.futures.put(correlationId, future);
try {
future.setSendFuture(send(record));
}
catch (Exception e) {
this.futures.remove(correlationId);
throw new KafkaException("Send failed", e);
}
scheduleTimeout(record, correlationId, replyTimeout == null ? this.defaultReplyTimeout : replyTimeout);
return future;
}
private void scheduleTimeout(ProducerRecord<K, V> record, CorrelationKey correlationId, Duration replyTimeout) {
this.scheduler.schedule(() -> {
RequestReplyFuture<K, V, R> removed = this.futures.remove(correlationId);
if (removed != null) {
this.logger.warn(() -> "Reply timed out for: " + record + WITH_CORRELATION_ID + correlationId);
if (!handleTimeout(correlationId, removed)) {
removed.setException(new KafkaReplyTimeoutException("Reply timed out"));
}
}
}, Instant.now().plus(replyTimeout));
}
/**
* Used to inform subclasses that a request has timed out so they can clean up state
* and, optionally, complete the future.
* @param correlationId the correlation id.
* @param future the future.
* @return true to indicate the future has been completed.
* @since 2.3
*/
protected boolean handleTimeout(@SuppressWarnings("unused") CorrelationKey correlationId,
@SuppressWarnings("unused") RequestReplyFuture<K, V, R> future) {
return false;
}
/**
* Return true if this correlation id is still active.
* @param correlationId the correlation id.
* @return true if pending.
* @since 2.3
*/
protected boolean isPending(CorrelationKey correlationId) {
return this.futures.containsKey(correlationId);
}
@Override
public void destroy() {
if (!this.schedulerSet) {
((ThreadPoolTaskScheduler) this.scheduler).destroy();
}
}
/**
* Subclasses can override this to generate custom correlation ids.
* The default implementation is a 16 byte representation of a UUID.
* @param record the record.
* @return the key.
* @deprecated in favor of {@link #setCorrelationIdStrategy(Function)}.
*/
@Deprecated
protected CorrelationKey createCorrelationId(ProducerRecord<K, V> record) {
return this.correlationStrategy.apply(record);
}
private static <K, V> CorrelationKey defaultCorrelationIdStrategy(
@SuppressWarnings("unused") ProducerRecord<K, V> record) {
UUID uuid = UUID.randomUUID();
byte[] bytes = new byte[16]; // NOSONAR magic #
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return new CorrelationKey(bytes);
}
@Override
public void onMessage(List<ConsumerRecord<K, R>> data) {
data.forEach(record -> {
Header correlationHeader = record.headers().lastHeader(this.correlationHeaderName);
CorrelationKey correlationId = null;
if (correlationHeader != null) {
correlationId = new CorrelationKey(correlationHeader.value());
}
if (correlationId == null) {
this.logger.error(() -> "No correlationId found in reply: " + record
+ " - to use request/reply semantics, the responding server must return the correlation id "
+ " in the '" + this.correlationHeaderName + "' header");
}
else {
RequestReplyFuture<K, V, R> future = this.futures.remove(correlationId);
CorrelationKey correlationKey = correlationId;
if (future == null) {
logLateArrival(record, correlationId);
}
else {
boolean ok = true;
if (record.value() == null) {
DeserializationException de = checkDeserialization(record, this.logger);
if (de != null) {
ok = false;
future.setException(de);
}
}
if (ok) {
this.logger.debug(() -> "Received: " + record + WITH_CORRELATION_ID + correlationKey);
future.set(record);
}
}
}
});
}
/**
* Return a {@link DeserializationException} if either the key or value failed
* deserialization; null otherwise. If you need to determine whether it was the key or
* value, call
* {@link ListenerUtils#getExceptionFromHeader(ConsumerRecord, String, LogAccessor)}
* with {@link ErrorHandlingDeserializer2#KEY_DESERIALIZER_EXCEPTION_HEADER} and
* {@link ErrorHandlingDeserializer2#VALUE_DESERIALIZER_EXCEPTION_HEADER} instead.
* @param record the record.
* @param logger a {@link LogAccessor}.
* @return the {@link DeserializationException} or {@code null}.
* @since 2.2.15
*/
@Nullable
public static DeserializationException checkDeserialization(ConsumerRecord<?, ?> record, LogAccessor logger) {
DeserializationException exception = ListenerUtils.getExceptionFromHeader(record,
ErrorHandlingDeserializer2.VALUE_DESERIALIZER_EXCEPTION_HEADER, logger);
if (exception != null) {
logger.error(exception, () -> "Reply value deserialization failed for " + record.topic() + "-"
+ record.partition() + "@" + record.offset());
return exception;
}
exception = ListenerUtils.getExceptionFromHeader(record,
ErrorHandlingDeserializer2.KEY_DESERIALIZER_EXCEPTION_HEADER, logger);
if (exception != null) {
logger.error(exception, () -> "Reply key deserialization failed for " + record.topic() + "-"
+ record.partition() + "@" + record.offset());
return exception;
}
return null;
}
protected void logLateArrival(ConsumerRecord<K, R> record, CorrelationKey correlationId) {
if (this.sharedReplyTopic) {
this.logger.debug(() -> missingCorrelationLogMessage(record, correlationId));
}
else {
this.logger.error(() -> missingCorrelationLogMessage(record, correlationId));
}
}
private String missingCorrelationLogMessage(ConsumerRecord<K, R> record, CorrelationKey correlationId) {
return "No pending reply: " + record + WITH_CORRELATION_ID
+ correlationId + ", perhaps timed out, or using a shared reply topic";
}
}