0

I am using Spring Cloud Stream.

How can I produce a Kafka message from a REST controller route handler method?

@RestController
public final class TransactionController {

    @PostMapping("/transactions")
    public void recordTransaction(final RecordTransaction recordTransaction) {
        // I want to produce a TransactionRecorded event through Kafka here
    }

}

1 Answers1

2

You can @Autowired StreamBridge in your Controller Bean and use it in the @PostMapping endpoint.

As documentation says... StreamBridge bean allows us to send data to an output binding effectively bridging non-stream application with spring-cloud-stream

Check documentation here. https://docs.spring.io/spring-cloud-stream/docs/3.1.0/reference/html/spring-cloud-stream.html#_sending_arbitrary_data_to_an_output_e_g_foreign_event_driven_sources

@Autowired
private StreamBridge streamBridge  

@PostMapping("/transactions")
public void recordTransaction(final RecordTransaction recordTransaction) {
    streamBridge.send("record_transaction-out-0", recordTransaction);
}
50qbits
  • 254
  • 2
  • 3