user14900768
user14900768

Reputation:

Spring Cloud Stream: how can I produce a Kafka message from a REST controller?

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
    }

}

Upvotes: 0

Views: 435

Answers (1)

50qbits
50qbits

Reputation: 274

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);
}

Upvotes: 2

Related Questions