Skip to content

GH-3067: Spring Kafka support multiple headers with same key. #3874

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2017-2025 the original author or authors.
* Copyright 2025 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.
Expand Down Expand Up @@ -48,6 +48,7 @@
* @author Gary Russell
* @author Artem Bilan
* @author Soby Chacko
* @author Sanghyoek An
*
* @since 1.3
*
Expand Down Expand Up @@ -324,12 +325,24 @@ else if (!(headerName.equals(JSON_TYPES)) && matchesForInbound(headerName)) {
populateJsonValueHeader(header, requestedType, headers);
}
else {
headers.put(headerName, headerValueToAddIn(header));
handleHeader(headerName, header, headers);
}
}
});
}

/**
* Handle non-reserved headers in {@link DefaultKafkaHeaderMapper}.
* @param headerName the header name.
* @param header the header instance.
* @param headers the target headers.
* @since 4.0.0
*/

protected void handleHeader(String headerName, Header header, final Map<String, Object> headers) {
headers.put(headerName, headerValueToAddIn(header));
}

private void populateJsonValueHeader(Header header, String requestedType, Map<String, Object> headers) {
Class<?> type = Object.class;
boolean trusted = false;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* Copyright 2017-2025 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.support;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.kafka.common.header.Header;

import org.springframework.kafka.retrytopic.RetryTopicHeaders;

/**
* Extended Header Mapper based on {@link DefaultKafkaHeaderMapper}.
* This Header Mapper manages header values as a list,
* except for certain reserved headers.
* Other behaviors are identical to {@link DefaultKafkaHeaderMapper}.
*
* @author Sanghyeok An
*
* @since 4.0.0
*
*/
public class MultiValueKafkaHeaderMapper extends DefaultKafkaHeaderMapper {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think that I agree about extra abstraction on the matter.
I think the existing HeaderMapper must support iterables for end-user headers.
So, we should expect some pattern for those custom headers which we can treat as iterable.
And I think that one should be on the in (from Kafka) only.
If we produce and some header is a collection, then populate it into Kafka headers as is.
On the other side, for convenience, we still should support first value mapping by default.
And map only those to collection values, which we have opted-in.

Make sense?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@artembilan
There are parts that I understand and parts that I don't.
It's been a while since I last worked with Kafka in my work, so I might be misunderstanding some aspects.
Please keep that in mind as you read this.

How can Spring Kafka anticipate a custom header pattern that is iterable?
Even if Spring Kafka expects a custom header to be iterable, users might always expect the header to be a single value.
What I mean is, users may have already written their code accordingly, like @Header("blahblah") String value.

To handle such cases, I think it would be necessary to add a public method that allows users to configure the pattern for iterable custom headers as a workaround.

If the headers that should be treated as iterable are managed with a whitelist approach,
I believe DefaultKafkaHeaderMapper could support iterable headers without requiring additional abstraction as you mentioned before.

I believe that by moving part of the logic from the MultiValueKafkaHeaderMapper class which I implement to DefaultKafkaHeaderMapper and simply adding a whitelist field,
spring kafka can support multi-header values while maintaining backward compatibility.

Overall, it makes sense to me 👍

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe the @Header("blahblah") String value should work. That annotation processor is able to extract single value from an iterable header.

Yes, I would expect some configuration property on the DefaultKafkaHeaderMapper to opt-in to those Kafka headers which have to be mapped to Message header as List.
We cannot use white and black words though. So, we need to come up with other name. Like headerAsListPattern. Or even vararg String... headerAsListPatterns. Where pattern has to follow org.springframework.util.PatternMatchUtils expectations.

On the mapping from Message to Kafka there is no need to think about pattern.
The trigger is simple: if Message is an iterable, then we put it into multi-header in Kafka record.


private final List<String> defaultSingleValueHeaderList = List.of(
KafkaHeaders.PREFIX,
KafkaHeaders.RECEIVED,
KafkaHeaders.TOPIC,
KafkaHeaders.KEY,
KafkaHeaders.PARTITION,
KafkaHeaders.OFFSET,
KafkaHeaders.RAW_DATA,
KafkaHeaders.RECORD_METADATA,
KafkaHeaders.ACKNOWLEDGMENT,
KafkaHeaders.CONSUMER,
KafkaHeaders.RECEIVED_TOPIC,
KafkaHeaders.RECEIVED_KEY,
KafkaHeaders.RECEIVED_PARTITION,
KafkaHeaders.TIMESTAMP_TYPE,
KafkaHeaders.TIMESTAMP,
KafkaHeaders.RECEIVED_TIMESTAMP,
KafkaHeaders.NATIVE_HEADERS,
KafkaHeaders.BATCH_CONVERTED_HEADERS,
KafkaHeaders.CORRELATION_ID,
KafkaHeaders.REPLY_TOPIC,
KafkaHeaders.REPLY_PARTITION,
KafkaHeaders.DLT_EXCEPTION_FQCN,
KafkaHeaders.DLT_EXCEPTION_CAUSE_FQCN,
KafkaHeaders.DLT_EXCEPTION_STACKTRACE,
KafkaHeaders.DLT_EXCEPTION_MESSAGE,
KafkaHeaders.DLT_KEY_EXCEPTION_STACKTRACE,
KafkaHeaders.DLT_KEY_EXCEPTION_MESSAGE,
KafkaHeaders.DLT_KEY_EXCEPTION_FQCN,
KafkaHeaders.DLT_ORIGINAL_TOPIC,
KafkaHeaders.DLT_ORIGINAL_PARTITION,
KafkaHeaders.DLT_ORIGINAL_OFFSET,
KafkaHeaders.DLT_ORIGINAL_CONSUMER_GROUP,
KafkaHeaders.DLT_ORIGINAL_TIMESTAMP,
KafkaHeaders.DLT_ORIGINAL_TIMESTAMP_TYPE,
KafkaHeaders.GROUP_ID,
KafkaHeaders.DELIVERY_ATTEMPT,
KafkaHeaders.EXCEPTION_FQCN,
KafkaHeaders.EXCEPTION_CAUSE_FQCN,
KafkaHeaders.EXCEPTION_STACKTRACE,
KafkaHeaders.EXCEPTION_MESSAGE,
KafkaHeaders.KEY_EXCEPTION_STACKTRACE,
KafkaHeaders.KEY_EXCEPTION_MESSAGE,
KafkaHeaders.KEY_EXCEPTION_FQCN,
KafkaHeaders.ORIGINAL_TOPIC,
KafkaHeaders.ORIGINAL_PARTITION,
KafkaHeaders.ORIGINAL_OFFSET,
KafkaHeaders.ORIGINAL_TIMESTAMP,
KafkaHeaders.ORIGINAL_TIMESTAMP_TYPE,
KafkaHeaders.CONVERSION_FAILURES,
KafkaHeaders.LISTENER_INFO,
RetryTopicHeaders.DEFAULT_HEADER_ATTEMPTS,
RetryTopicHeaders.DEFAULT_HEADER_ORIGINAL_TIMESTAMP,
RetryTopicHeaders.DEFAULT_HEADER_BACKOFF_TIMESTAMP);

private final Set<String> singleValueHeaders = new HashSet<>(this.defaultSingleValueHeaderList);

/**
* Adds headers that the {@link MultiValueKafkaHeaderMapper} should handle as single values.
* @param headerName the header name.
*/
public void addSingleValueHeader(String headerName) {
this.singleValueHeaders.add(headerName);
}

@Override
protected void handleHeader(String headerName, Header header, Map<String, Object> headers) {
if (this.singleValueHeaders.contains(headerName)) {
headers.put(headerName, headerValueToAddIn(header));
}
else {
Object values = headers.getOrDefault(headerName, new ArrayList<>());

if (values instanceof List) {
@SuppressWarnings("unchecked")
List<Object> castedValues = (List<Object>) values;
castedValues.add(headerValueToAddIn(header));
headers.put(headerName, castedValues);
}
else {
headers.put(headerName, headerValueToAddIn(header));
}

}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
* @author Gary Russell
* @author Dariusz Szablinski
* @author Biju Kunjummen
* @author Sanghyeok An
*/
public class MessagingMessageConverter implements RecordMessageConverter {

Expand All @@ -83,6 +84,15 @@ public MessagingMessageConverter() {
this(msg -> msg.getHeaders().get(KafkaHeaders.PARTITION, Integer.class));
}

/**
* Construct an instance that uses given HeaderMapper.
* @param headerMapper the Header mapper.
* @since 4.0.0
*/
public MessagingMessageConverter(KafkaHeaderMapper headerMapper) {
this(msg -> msg.getHeaders().get(KafkaHeaders.PARTITION, Integer.class), headerMapper);
}

/**
* Construct an instance that uses the supplied partition provider function. The
* function can return null to delegate the partition selection to the kafka client.
Expand All @@ -100,6 +110,18 @@ public MessagingMessageConverter(Function<Message<?>, @Nullable Integer> partiti
this.partitionProvider = partitionProvider;
}

/**
* Construct an instance that uses the supplied partition provider function and given HeaderMapper.
* @param partitionProvider the provider.
* @param headerMapper the Header mapper.
* @since 4.0.0
*/
public MessagingMessageConverter(Function<Message<?>, @Nullable Integer> partitionProvider, KafkaHeaderMapper headerMapper) {
Assert.notNull(partitionProvider, "'partitionProvider' cannot be null");
this.headerMapper = headerMapper;
this.partitionProvider = partitionProvider;
}

/**
* Generate {@link Message} {@code ids} for produced messages. If set to {@code false},
* will try to use a default value. By default set to {@code false}.
Expand Down
Loading