I have a spring-webflux handler named WordListenerHandler which I can request a HTTP GET from the browser. This request is a stream of Long using Flux: .body(Flux.interval(Duration.ofSeconds(1)).log(), Long.class) so it continually update the HTML without refreshing the page. I want to show the messages of a kafka topi instead of the stream of Long values. So I have the consumer method onMessage(ConsumerRecord<String, String> consumerRecord) which is receiving messages and I am populating a Queue<String> stringStream. My idea is to use this queue on the HTTP GET method with Flux.fromStream. But is is static and I have to refresh the browser to see the updates. How do make the HTTP GET stream continually get data?
@Component
public class WordListenerHandler {
private final String WORDS_STREAMING_OUTPUT_TOPIC_NAME = "streaming-words-output-topic";
Queue<String> stringStream = new LinkedList<String>();
public Mono<ServerResponse> fluxWordCountStream(ServerRequest serverRequest) {
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_STREAM_JSON)
// DOES NOT WORK. i HAVE TO REFRESH THE BROWSER
.body(Flux.fromStream(stringStream.stream()), String.class);
// THIS WORKS AND I CAN CONTINUALLY SEE MY BROWSER UPDATE WITHOUT REFRESHING IT
// .body(Flux.interval(Duration.ofSeconds(1)).log(), Long.class);
}
@KafkaListener(topics = {WORDS_STREAMING_OUTPUT_TOPIC_NAME})
public void onMessage(ConsumerRecord<String, String> consumerRecord) throws JsonProcessingException {
log.info("ConsumerRecord received: {}", consumerRecord);
String message = consumerRecord.key() + " : " + consumerRecord.value() + "\n";
stringStream.add(message);
}
}