SpringBoot整合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;
@RestController
public class ServerSentEventController {
@GetMapping(value = "/subscribe", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public ResponseEntity<PushBuilder> subscribe() {
// 获取PushBuilder对象
PushBuilder pushBuilder = request.getPushBuilder();
if (pushBuilder != null) {
// 设置推送内容的URL
pushBuilder.path("/publish");
// 设置推送内容的Content-Type
PushStreamHttpHeaders headers = new PushStreamHttpHeaders();
headers.setContentType(MediaType.TEXT_EVENT_STREAM);
// 返回ResponseEntity,包含PushBuilder对象和推送头部信息
return ResponseEntity.ok()
.headers(headers)
.body(pushBuilder);
}
return ResponseEntity.notFound().build();
}
@GetMapping("/publish")
public void publish(PrintWriter writer) {
// 使用PrintWriter发送SSE数据
writer.print("data: Hello, Server-Sent Events!\n\n");
writer.flush(); // 确保消息已经发送
}
}
这段代码演示了如何在Spring Boot应用中使用Server-Sent Events(SSE)进行服务端推送。/subscribe
端点使用PushBuilder
来推送/publish
端点的内容。/publish
端点则使用PrintWriter
来发送SSE格式的文本数据。这个例子简单明了地展示了如何使用Spring Boot来实现SSE推送功能。
评论已关闭