如何写一个web api回复非常缓慢与无限流的文本使用java?



我想写一个web api,使用java在无限流中每5秒返回相同的文本。有哪些可能的方法?怎么做呢?

的例子:

curl 'https://localhost:8080/abcd'

响应如下:

"some text"
.
.<wait 5 seconds>
.
"some text"
.
.<wait 5 seconds>
.
"some text"
.
.
etc...
@SpringBootApplication
public class InfinitetextApplication {
public static void main(String[] args) {
SpringApplication.run(InfinitetextApplication.class, args);
}
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@RestController
static class InfiniteText {
private TaskScheduler taskScheduler;
public InfiniteText(TaskScheduler taskScheduler) {
this.taskScheduler = taskScheduler;
}
@GetMapping("/")
public ResponseEntity<ResponseBodyEmitter> textStream() throws IOException {
ResponseBodyEmitter rbe = new ResponseBodyEmitter();
sendMessage(rbe);
return ResponseEntity.ok()
.contentType(MediaType.TEXT_PLAIN)
.body(rbe);
}
private void sendMessage(ResponseBodyEmitter rbe) {
try {
rbe.send("Hellon");
taskScheduler.schedule(() -> sendMessage(rbe), inFiveSeconds());
} catch (IOException e) {
rbe.completeWithError(e);
throw new UncheckedIOException(e);
}
}
private Instant inFiveSeconds() {
return Instant.now()
.plusSeconds(5);
}
}
}

当你说"无限流";我相信你正在寻找"反应流"。可能你正在寻找Spring Reactive Web而不是Spring Web MVC

Spring Reactive Web,也称为Spring Web Flux,它使用Netty作为非阻塞Web服务器,而不是使用Tomact 9作为Spring MVC(阻塞)。

<<p>Web控制器/strong>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
@RequestMapping("api/read")
@CrossOrigin
public class ReadController  {
@Autowired
private ElementRepo elementRepo;
@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Element> getAll(){
return elementRepo.flux();
}
}
<<p>数据源/strong>
@Repository
public class ElementRepo {
public  Flux<Element> flux() {
return Flux
.just({something....}
.delayElements(Duration.ofSeconds(5));
}
}

使用Spring Webflux

选项# 1

@GetMapping("")   
public Flux<ServerSentEvent<String>> getStreamEvents() {
return Flux.interval(Duration.ofSeconds(5))
.map(sequence -> ServerSentEvent.<String>builder()
.id(String.valueOf(sequence))
.event("periodic-event")
.data("something...")
.build());
}

选项# 2

@GetMapping(path = "/", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamFlux() {
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> "Flux - " + LocalTime.now().toString());
}

最新更新