Reputation: 315
I was trying to send a message with key, value pair using spring cloud stream. I am not able to find any API for that. org.springframework.messaging.MessageChannel only has payload as part of send function.Using Kafka Template this can be achieved although. Is that the only way to produce key,value kind of message.As KafkaTemplate is part of spring for apache kafka, i was hoping there is a abstraction available for the same in spring cloud stream. Please suggest.
Thanks,
Upvotes: 3
Views: 4397
Reputation: 6106
For the purpose of your question you can look at spring-cloud-stream as higher level abstraction over more low level APIs such as spring-kafka (if kafka binder is used), spring-integration etc. In other words you don't need to either send or receive anything explicitly within the scope of the framework. It will do the sending and receiving for you; That's the core feature of the framework - to bind execution of your code to input and output destinations managed by your broker.
All you need to do for your case is produce a Message
. For example, here is a fully functioning application
@SpringBootApplication
public static class SupplierConfiguration {
@Bean
public Supplier<String> stringSupplier() {
return () -> "Hello from Supplier";
}
}
While all you did is produced a String the framework will wrap it into Message and will send it to Kafka (providing you're using Kafka binder).
If you need to control explicitly the value of the key, you can return an actual instance of the Message with kafka_messageKey
set. For example;
@SpringBootApplication
public static class SupplierConfiguration {
@Bean
public Supplier<Message<?>> stringSupplier() {
return () -> MessageBuilder.withPayload("Hello from Supplier")
.setHeader(KafkaHeaders.MESSAGE_KEY, "blah")
.build();
}
}
You can read more about it here
Also, notice we're moving away from annotation-based programming model and into a much simpler functional model.
Upvotes: 7