自学内容网 自学内容网

Springboot sse 示例

java Ctr层代示例代码


import org.springframework.http.MediaType;
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;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/sseDemo")
public class SseDemoCtr {

    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    @GetMapping(value = "/test", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter test() {
        SseEmitter emitter = new SseEmitter();

        executorService.submit(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    // 发送SSE事件
                    emitter.send(SseEmitter.event().data("这是一段测试消息 " + i));
                    // 模拟一些处理时间
                    Thread.sleep(1000);
                }
                // 完成SSE流
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                // 发生错误时关闭SSE流
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }
}

前端js核心代码


    <script>

        const evtSource = new EventSource('/sseDemo/test');
        const messages = document.getElementById('messages');
 
        evtSource.onmessage = function(event) {
            const newElement = document.createElement("p");
            const eventObject = JSON.parse(event.data);
            newElement.textContent = "Message: " + eventObject.message + " at " + eventObject.timestamp;
            messages.appendChild(newElement);
        };

    </script>


原文地址:https://blog.csdn.net/hongbowu/article/details/145287484

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!