在本文中,我们将向您展示如何使用服务器发送的事件开发反应式Web应用程序
- Spring Boot 2.1.2发布
- Spring WebFlux 5.1.4。发布
- Thymeleaf 3.0.11。发布
- JUnit 5.3.2
- Maven 3
在Spring中,返回JSON和标头MediaType.TEXT_EVENT_STREAM_VALUE
@RestController
public class CommentController {
@GetMapping(path = "/comment/stream",
produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Comment> feed() {
//...
}
}
在Javascript中,使用EventSource
将请求发送到上述端点。
function loadComments () {
this.source = null;
this.start = function () {
this.source = new EventSource("/comment/stream");
this.source.addEventListener("message", function (event) {
var comment = JSON.parse(event.data);
//... update somewhere
});
this.source.onerror = function () {
this.close();
};
};
this.stop = function() {
this.source.close();
}
}
comment = new loadComments();
window.onload = function() {
comment.start();
};
window.onbeforeunload = function() {
comment.stop();
}
1.项目目录
![项目目录](https://i-blog.csdnimg.cn/blog_migrate/dd0dbfa9f12d06a1a24a1d39d86c3f6e.png)
2. Maven
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.spring.reactive</groupId>
<artifactId>webflux-thymeleaf-sse</artifactId>
<version>1.0</version>
<properties>
<java.version>1.8</java.version>
<junit-jupiter.version>5.3.2</junit-jupiter.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>
<dependencies>
<!-- webflux reactive -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- exclude junit 4, prefer junit 5 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- junit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>