【发布时间】:2026-02-04 07:15:01
【问题描述】:
我已经定义了两个 HTTP GET API /test-mono 和 /test-no-mono,除了 /test-mono 使用 Mono 返回类型之外,两者完全相同。 HelloControllerSpec 使用 100 个线程池测试两个 API 1000 次,/test-no-mono 需要 45 秒,但 /test-mono 需要超过 4 分钟,为什么?看起来 /test-no-mono 的默认并发配置比 /test-mono 好得多。
完整代码在https://github.com/soumitrak/micronaut-server
@Controller("/")
class HelloController {
@Get("test-mono/{id}", produces = arrayOf(MediaType.APPLICATION_JSON))
fun test_mono(id: String): Mono<String> {
Thread.sleep(4000)
return Mono.just("Hello World! $id")
}
@Get("test-no-mono/{id}", produces = arrayOf(MediaType.APPLICATION_JSON))
fun test_no_mono(id: String): String {
Thread.sleep(4000)
return "Hello World! $id"
}
}
$ ./gradlew 清洁测试
任务:测试
sk.test.server.HelloControllerSpec STANDARD_OUT
09:37:32.473 [Test worker] INFO i.m.context.env.DefaultEnvironment - Established active environments: [test]
sk.test.server.HelloControllerSpec > 使用 Mono STANDARD_OUT
09:37:34.262 [Test worker] INFO sk.test.server.HelloControllerSpec - Tests using mono
09:41:46.972 [Test worker] INFO sk.test.server.HelloControllerSpec - Done tests using mono
测试在 > 4 分钟内运行
sk.test.server.HelloControllerSpec > 没有 Mono STANDARD_OUT
09:41:46.975 [Test worker] INFO sk.test.server.HelloControllerSpec - Tests without mono
09:42:27.216 [Test worker] INFO sk.test.server.HelloControllerSpec - Done tests without mono
45 秒内完成相同的测试。
“/test-mono”速度慢的原因是什么?如何提高此 API 的性能?
【问题讨论】:
-
可能是因为您对
/test-mono的请求正在事件循环线程(它们应该是)上处理。我认为nThreads的默认值是处理器数量乘以 2。您可以使用micronaut.executors.io.nThreads=50之类的内容更改该值。