Search code examples
apache-kafkaspring-cloud-streamspring-cloud-stream-binder-kafka

How to set Key in Stream cloud function


I'm using stream cloud stream in order to receive and publish events to kafka I also use the functional programing model.

Say I have this bean definition:

@Bean
public Function<InputMsg,OutputMsg> handle(){
//do some calculation that returns OutputMsg
}

How can I controlor the key of the message? that is I want to send OutputMsg event back to kafka but I don't know how to control the key , only the value (OutputMsg in my example)


Solution

  • Use Function<Message<InputMsg>, Message<OutputMsg>> instead.

    In the inbound message, the key is in msg.getHeaders().get(KafkaHeaders.RECEIVED_MESSAGE_KEY); to set the key in the outbound message, set KafkaHeaders.MESSAGE_KEY.