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?

推荐答案

摘要

通过相同的终点发送多个,这不是REST API个场景.一般来说,我们经常使用长连接来处理这种情况,有很多技术可供 Select ,比如WebSocket、TCP协议、Socket,但它们都太重了,只需向指定主机发送一条消息就可以配置这么多.

简而言之,有Server-Sent Events个可以很容易地解决你的问题,我会在 spring 演示这项技术的Bacic演示,你也可以阅读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>

在本例中,SseController中的/SSE/Events端点返回一个SseEmitter,并且使用一个单独的线程来异步发送事件.客户端上的JavaScript代码使用EventSourceAPI来监听事件并更新HTML内容.

请记住使用适当的依赖项配置您的Spring Boot应用程序,并且您可能需要在生产场景中适当地处理异常和清理.

附录

  <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>

你可以在下面的包路径中找到主要类(可能与其他Spring Boot版本不同)

org.springframework.web.servlet.mvc.method.annotation.SseEmitter

Java相关问答推荐

如何审查Java dtos中的自定义注释字段?

Java:根据4象限中添加的行数均匀分布行的公式

Java取消任务运行Oracle查询通过JDBC—连接中断,因为SQLSTATE(08006),错误代码(17002)IO错误:套接字读取中断

Android Studio—java—在onBindViewHolder中,将断点和空白添加到BackclerView中

如何配置ActiveMQ Artemis以使用AMQP 1.0和其他协议与Java

对运行在GraalVM-21上的JavaFX应用程序使用分代ZGC会警告不支持JVMCI,为什么?

不推荐使用的Environment.getExternalStorageDirectory().getAbsolutePath()返回的值不同于新的getExternalFilesDir(空)?

编译多个.Java文件并运行一个依赖于用户参数的文件

相同的Java SerializedLambda为implMethodKind返回不同的结果

Log4j与jdk21兼容吗?

在Java中将int[]矩阵添加到ArrayList中,但出现错误

将关闭拍卖的TimerService

插入中的JOOQ序列,设置为VS值

如何在字节数组中反转UTF-8编码?

处理4.3问题:javax.xml.ind包不存在(&Q;).您可能在学习GitHub教程时遗漏了库.&Q

在ECLIPSE上的M1 Pro上运行JavaFX的问题

在Java中使用StorageReference将数据从Firebase存储添加到数组列表

如何设置默认序列生成器分配大小

java.lang.ClassCastException:com.google.firebase.FirebaseException无法转换为com.google.fire base.auth.FirebaseAuthException

Spring Boot Security-每个端点都被403禁止,Spring记录一个BasicErrorController#错误(HttpServlet请求)