Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send multiple time response from one endpoint in Java springboot?

Scenario:
I have 30 testcases for end-to-end process flow that includes (scheduler, producer and consumer). So, I'm automating the 30 testcase in java springmvc web application. I have created an endpoint which is to start testing, then it will run 30 testcase one after other in order, I have created 30 methods for each testcase, each test case approx takes 5 min to complete because (have to execute scheduler, producer and consumer). so, after one test case is complete, I want to show in UI the status and message, I don't want to wait till all the 30 testcase completion then show status of all testcase. How to achieve this using rest endpoint?

like image 509
Seriously Avatar asked Apr 06 '26 09:04

Seriously


1 Answers

Summary

send multiple via same end point , it is not REST API scenario. In general , we often use Long connection to handle this scenario , there many tech to choose like websocket , tcp protocol , socket , but all of them are too heavy , just send a mejssage to specified host may configure so much .

Solution

In a nutshell , there is Server-Sent Events could easy solve your problem , i would demonstrae bacic demo for this tech in spring , also you can read offical spring sse doc

1. set up endpoint in spring

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@RestController
@RequestMapping("/sse")
public class SseController {

    @GetMapping("/events")
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter();

        // Asynchronous processing to send events
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    // Send events every 1 second
                    emitter.send(SseEmitter.event().name("message").data("Event " + i));

                    Thread.sleep(1000);
                }
                // Signal the end of the event stream
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }
}


connect endpoint by client side


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Example</title>
</head>
<body>
    <h1>SSE Example</h1>
    <div id="sse-events"></div>

    <script>
        const eventSource = new EventSource('/sse/events');

        eventSource.onmessage = function (event) {
            const eventsDiv = document.getElementById('sse-events');
            eventsDiv.innerHTML += `<p>${event.data}</p>`;
        };

        eventSource.onerror = function (error) {
            console.error('EventSource failed:', error);
            eventSource.close();
        };
    </script>
</body>
</html>

In this example, the /sse/events endpoint in the SseController returns an SseEmitter, and a separate thread is used to send events asynchronously. The JavaScript code on the client side uses the EventSource API to listen for events and update the HTML content.

Remember to configure your Spring Boot application with appropriate dependencies, and you may need to handle exceptions and cleanup appropriately in a production scenario.

Appendix

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.4.2</version> // replace appropriate  version , 3.0.0 or else later is ok
      </dependency>

you can find major class at following package path (may different from other spring boot version )

org.springframework.web.servlet.mvc.method.annotation.SseEmitter
like image 81
Peng Avatar answered Apr 08 '26 23:04

Peng