我有这个 GET 控制器
@GetMapping("/test")
public Flux<String> test() {
return Flux.just("Test1", "test2")
.delayElements(Duration.ofSeconds(1))
.log();
}
当我调用这个方法时,需要 2 秒才能完成,日志打印 onNext 和 onComplete 这意味着它正在发射,但返回为空。
有什么想法吗?
如果我更改此设置并使用 block() 方法并删除 Flux,它将返回“Test1”和“Test2”。
有了这样的控制器,你的代码就可以在我的电脑上运行了
package com.example.flux_demo;
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 MyController {
@GetMapping("/test")
public Flux<String> test() {
return Flux.just("Test1", "test2")
.delayElements(Duration.ofSeconds(1))
.log();
}
}
build.gradle.kts
plugins {
java
id("org.springframework.boot") version "3.3.0"
id("io.spring.dependency-management") version "1.1.5"
}
group = "com.example"
version = "0.0.1-SNAPSHOT"
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-webflux")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("io.projectreactor:reactor-test")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.withType<Test> {
useJUnitPlatform()
}