Server-Sent Events springboot demo
时间: 2023-07-07 15:45:07 浏览: 74
以下是一个基于Spring Boot的Server-Sent Events示例:
首先,在pom.xml文件中添加以下依赖项:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
接下来,创建一个名为“ServerSentEventController”的新类,该类将处理Server-Sent Events请求:
```
import java.time.LocalTime;
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 ServerSentEventController {
@GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter serverSentEvent() {
SseEmitter emitter = new SseEmitter();
LocalTime currentTime = LocalTime.now();
// 发送当前时间
emitter.send(SseEmitter.event().data("Current time: " + currentTime.toString()));
// 定时发送时间
Thread thread = new Thread(() -> {
try {
while (true) {
Thread.sleep(5000);
currentTime = LocalTime.now();
emitter.send(SseEmitter.event().data("Current time: " + currentTime.toString()));
}
} catch (Exception e) {
emitter.complete();
}
});
thread.start();
return emitter;
}
}
```
在上面的代码中,我们创建了一个名为“serverSentEvent”的控制器方法,该方法返回一个SseEmitter对象,该对象将用于发送Server-Sent Events。在这个方法中,我们首先发送当前时间,然后设置一个线程,每隔5秒发送一次当前时间,直到连接关闭或发生异常为止。
最后,在Spring Boot应用程序的主类上添加@EnableWebMvc注释:
```
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@EnableWebMvc
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
现在,您可以启动应用程序并访问“http://localhost:8080/sse”来查看Server-Sent Events的示例。您应该能够在浏览器中看到当前时间,并且每隔5秒钟更新一次。