Search code examples
javaspringspring-bootspring-kafkaspring-cloud-stream

How to publish message to 2 kafka topics based on condition - spring cloud stream


Currently i have a spring clound funtion which consumes a topic and publish in to another topic. But for particular condition i need to publish message to another topic. Basically need to publish message to multiple topic from spring cloud function.

Current code snippets

@Bean
public Function<Message<InputMessage>, Message<OutputMessage>>
    messageTransformer(){
    return new KafkaTransformer();
    }


public class KafkaTransformer
    implements Function<
    Message<InputMessage>, Message<OutputMessage>> {

  @Override
  public Message<OutputMessage> apply(
      Message<InputMessage> inputMessage) {
    try {
      Message<OutputMessage> outputMessage = process(inputMessage);
      return outputMessage;
    } catch (Exception e) {
      // need to send message to another topic ( which is other than dlq).
    }
  }
}

spring.cloud.stream.bindings.messageTransformer-in-0.destination=input.topic
spring.cloud.stream.bindings.messageTransformer-out-0.destination=output.topic
spring.cloud.function.definition=messageTransformer

Solution

  • Did you look into using StreamBridge API for this? Sounds like that should work for what you are looking for. Here are the docs.