在Spring Boot中整合SSE(Server-Sent Events)实现后端主动推送数据到前端的示例代码如下:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 
@RestController
public class SseController {
 
    @GetMapping(path = "/stream-sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter();
 
        // 在新线程中模拟数据生成并发送
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    emitter.send("data:" + i + "\n\n"); // 发送数据给客户端
                    Thread.sleep(1000); // 每秒发送一次
                }
                emitter.complete(); // 完成发送
            } catch (Exception e) {
                emitter.completeWithError(e); // 发送异常
            }
        }).start();
 
        return emitter;
    }
}前端代码可以使用JavaScript的EventSource API来接收这些事件:
<!DOCTYPE html>
<html>
<head>
    <title>SSE Example</title>
</head>
<body>
    <h1>Server-Sent Events Demo</h1>
    <script>
        const eventSource = new EventSource('/stream-sse');
 
        eventSource.onmessage = function(e) {
            console.log(e.data);
            // 处理接收到的数据
        };
 
        eventSource.onerror = function(e) {
            console.error(e);
            // 处理错误
        };
 
        eventSource.onopen = function(e) {
            console.log("Connection opened...");
            // 处理连接开启
        };
    </script>
</body>
</html>在这个例子中,后端通过SseEmitter对象提供SSE服务,并在新线程中循环发送数据。前端通过EventSource对象接收这些事件,并在控制台中打印出来。这个简单的例子演示了如何实现服务端向客户端的单向数据推送。