Search code examples
springapache-kafkareactive-programmingspring-webfluxspring-cloud-stream

How to publish a message to Kafka topic using spring cloud stream in reactive way [using webflux]?


  • Publish a message to kafka topic without using StreamBridge as it uses deprecated components.

Solution

  • Using reactor API:

    All you need to do is declare a Supplier<Flux<whatever>> which returns EmitterProcessor from the reactor API (see Reactive Functions support for more details) to effectively provide a bridge between the actual event source (foreign source) and spring-cloud-stream. All you need to do now is feed the EmitterProcessor with data via EmitterProcessor#onNext(data) operation.
    Quoted from spring cloud stream docs

    @SpringBootApplication
    @Controller
    public class WebSourceApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(WebSourceApplication.class);
        }
    
        EmitterProcessor<String> processor = EmitterProcessor.create();
    
        @RequestMapping
        @ResponseStatus(HttpStatus.ACCEPTED)
        public void delegateToSupplier(@RequestBody String body) {
            processor.onNext(body);
        }
    
        @Bean
        public Supplier<Flux<String>> supplier() {
            return () -> this.processor;
        }
    }
    

    To send a message use curl curl -H "Content-Type: text/plain" -X POST -d "hello from the other side" http://localhost:8080/