Functional programming, Kafka and REST – how to send data?

Let’s say we have a REST endpoint and we want to send a message via Spring’s Cloud Stream Kafka. Easy? Yes, if we’re using a legacy annotation model – yes. But what if we want to send a Kafka message, when someone calls our REST endpoint?

Spring calls it “sending arbitrary data to an output“. But let’s create an example for it:

# application.yml
spring:
   cloud:
    stream:
      bindings:
        objectPusher-out-0:
          destination: customer
          content-type: application/json
          group: 'my-amazing-group'

      kafka:
        binder:
          brokers: localhost:9092
          replicationFactor: 1 

And code sample is easy:

@Autowired
private StreamBridge streamBridge;

// ...
var message = MyNewCustomObject(<properties_here>);
streamBridge.send("objectPusher-out-0", message);

And that’s it – message has been sent to Kafka topic “customer”.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *