springboot实现gpt的eventstream案例
一、maven坐标
引入webflux依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
二、democontroller
Java
package org.example.webfluxdemo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.time.Duration;
@RestController
public class EventStreamController {
@GetMapping(value = "/events", produces = "text/event-stream")
public Flux<String> events() {
return Flux
.interval(Duration.ofSeconds(1)) // 每1秒产生一个数据
.map(l -> "Data: " + l); // 将长整型数据转换为字符串
}
}