1:配置pom.xml,使用flux需要注释掉spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
2:controller控制类
package com.test.order.controller;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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;
import reactor.core.publisher.Mono;
import java.awt.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@RestController
@RequestMapping("/test")
@Slf4j
@CrossOrigin
public class TestController {
@GetMapping("/one")
public Mono<String> one() {
log.info("mono1");
Mono<String> hello = Mono.fromSupplier(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "one";
});
log.info("mono2");
hello.subscribe(d -> System.out.println(d));
return hello;
}
@SneakyThrows
@GetMapping("/two")
public String two() {
System.out.println("******");
TimeUnit.SECONDS.sleep(5);
return "two";
}
@SneakyThrows
@GetMapping("/three")
public String three() {
log.info("stringCompletableFuture1");
CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "three";
});
log.info("stringCompletableFuture2");
return "three";
}
@GetMapping(value = "/four",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> four() {
log.info("Flux1");
Flux<String> flux = Flux.fromStream(
IntStream.range(1, 5).mapToObj(d -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "flux data--" + d;
})
);
log.info("Flux2");
return flux;
}
}