提问人:Drex 提问时间:10/14/2023 更新时间:10/14/2023 访问量:67
在Spring Boot应用程序中使用Network Request函数将关键字挂起为冗余
Suspend keyword as redundant with Network Request function in Spring Boot Application
问:
我一直在深入研究 Kotlin 协程,发现在使用 Kotlin 和协程时,挂起函数可以简化异步和非阻塞代码的创建。在 Android 应用程序中,将网络请求作为挂起函数对于防止阻塞主线程至关重要。
但是,在Spring Boot应用程序中,主线程的概念并不那么突出,在某些情况下,我们需要等待网络调用返回,然后再继续执行后续步骤,这似乎有点“阻塞”。我甚至尝试将 suspend 关键字应用于我的客户端调用,并在协程中启动它们。有趣的是,Kotlin 有时会建议“suspend”关键字是多余的。
这就提出了一个问题,即网络请求或其他 I/O 绑定操作是否真的可以被视为或实现为 Spring Boot 上下文中的挂起方法。如果有一种方法可以将它们实现为挂起函数,这将给 REST 调用带来什么好处?
// suspend here is redundant...in fact, if this call takes x seconds, my API request thread will be blocked for x seconds
suspend fun makeHttpRequest(): String {
val client = HttpClient()
val response = client.get<String>("https://example.com/api/endpoint")
return response
}
fun main() {
val numberOfThreads = 4 // Adjust as needed
val threadPool = newFixedThreadPoolContext(numberOfThreads, "CustomThreadPool")
runBlocking {
repeat(numberOfThreads) {
GlobalScope.launch(Dispatchers.Default + threadPool) {
val result = makeHttpRequest()
// Process the result here
}
}
}
}
答:
1赞
amanin
10/14/2023
#1
当且仅当您使用 Spring Webflux 时,异步/非阻塞网络堆栈才与协程一起使用。
Spring 通过 Reactor(反应流)和 Netty 提供与协程的非阻塞兼容性。
您可以在以下博客文章部分获取更多信息:带有协程 API 的 Webflux。
评论
0赞
Drex
10/15/2023
谢谢,当将 Java CompletableFuture 和 Kotlin 协程一起使用时,我的网络请求会变得异步和非阻塞吗?
0赞
amanin
10/16/2023
@Drex:我不确定CompletableFuture/suspend 函数的兼容性。我还取决于 Spring 如何处理 CompletableFuture 返回值。而且,自最新的 JDK 版本以来,还需要考虑虚拟线程,这可以帮助使代码不阻塞。
评论
suspend
不会使阻止呼叫被魔法暂停。您使用的库必须兼容,并且由于是 Kotlin 独有的功能,因此 Java 库不会兼容。因此,要么你必须实现自己的包装器,要么找到一个库,使你的网络请求协同兼容。suspend
withContext(Dispatchers.IO)
suspendCancellableCoroutine