使用Spring Boot实现Server-Sent Events(SSE)的完整指南
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import org.springframework.http.concurrent.PushStreamHttpHeaders;
import javax.servlet.http.PushBuilder;
import java.io.PrintWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@RestController
public class ServerSentEventsController {
@GetMapping(path = "/subscribe", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public ResponseEntity<PushStreamHttpHeaders> subscribe(PushBuilder pushBuilder) {
PushStreamHttpHeaders headers = new PushStreamHttpHeaders();
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
try {
PrintWriter writer = pushBuilder.pushToTarget("/queue/events")
.setContentType(MediaType.TEXT_EVENT_STREAM)
.getWriter();
writer.printf("data: %s%n%n", "Initializing connection...");
writer.flush();
// 模拟发送事件
for (int i = 0; i < 5; i++) {
writer.printf("data: %s%n%n", "Event " + i);
writer.flush();
Thread.sleep(1000);
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
});
return ResponseEntity.ok().headers(headers).build();
}
}
这段代码示例展示了如何在Spring Boot应用中使用PushBuilder
来推送Server-Sent Events。它定义了一个简单的REST接口/subscribe
,当被调用时,它会启动一个新线程来发送事件。每个事件都以"data: "
开头,并以换行符结束,然后通过PushBuilder
的pushToTarget
方法推送到客户端的/queue/events
路径。这个例子提供了一个简单的模型,用于理解如何在实际应用中实现SSE。
评论已关闭