Spring 休息 API 使用 Deferred<> 调用服务
Spring Rest API calling service with Deffered<>
我的代码可以正常运行,但不确定我是否正确实现了它。
我有一个服务层,它使用 Retrofit 调用 Youtrack API,进行一些 post 过滤和 returns 问题列表。下面的代码是简化版的,但应该足够做一张图了。
suspend fun getProjectIssuesFromYt(
project: String,
youTrackInstance: YouTrackInstance,
after: Int,
max: Int
): List<Issues> = coroutineScope {
val service = Youtrack.getYoutrack(youTrackInstance).service
val deferreds: Deferred<List<Issues>> =
async(Dispatchers.Default) {
service.getIssuesByProject(
project = project, max = max,
after = after
).bodyList()
}
deferreds.await()
}
如何从 REST api 调用此服务?唯一有效的解决方案是使用 runBlocking
调用它,但我认为这不是可行的方法。
@GetMapping("/getProjectIssuesFromYt")
fun getProjectIssuesFromYt(
project: String,
youTrackInstance: YouTrackInstance,
after: Int,
max: Int
): List<Issues> = runBlocking {
clientService.getProjectIssuesFromYt(
project = project,
youTrackInstance = youTrackInstance,
after = after,
max = max
)
}
我确实尝试过暂停我的控制器功能并且 运行 它没有运行阻塞,但是我收到了一个错误。
"Parameter specified as non-null is null: method kotlinx.coroutines.internal.ScopeCoroutine.<init>, parameter context",
提前谢谢你,
马尔科
如果您正在使用 Spring MVC:
在 Spring Web Flux 中,Kotlin 协程仅可作为 Java 的 Project Reactor 的替代品。
Spring MVC 控制器在设计上是阻塞的,这就是为什么它们不能作为挂起函数实现的原因。
https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow
我的代码可以正常运行,但不确定我是否正确实现了它。
我有一个服务层,它使用 Retrofit 调用 Youtrack API,进行一些 post 过滤和 returns 问题列表。下面的代码是简化版的,但应该足够做一张图了。
suspend fun getProjectIssuesFromYt(
project: String,
youTrackInstance: YouTrackInstance,
after: Int,
max: Int
): List<Issues> = coroutineScope {
val service = Youtrack.getYoutrack(youTrackInstance).service
val deferreds: Deferred<List<Issues>> =
async(Dispatchers.Default) {
service.getIssuesByProject(
project = project, max = max,
after = after
).bodyList()
}
deferreds.await()
}
如何从 REST api 调用此服务?唯一有效的解决方案是使用 runBlocking
调用它,但我认为这不是可行的方法。
@GetMapping("/getProjectIssuesFromYt")
fun getProjectIssuesFromYt(
project: String,
youTrackInstance: YouTrackInstance,
after: Int,
max: Int
): List<Issues> = runBlocking {
clientService.getProjectIssuesFromYt(
project = project,
youTrackInstance = youTrackInstance,
after = after,
max = max
)
}
我确实尝试过暂停我的控制器功能并且 运行 它没有运行阻塞,但是我收到了一个错误。
"Parameter specified as non-null is null: method kotlinx.coroutines.internal.ScopeCoroutine.<init>, parameter context",
提前谢谢你,
马尔科
如果您正在使用 Spring MVC: 在 Spring Web Flux 中,Kotlin 协程仅可作为 Java 的 Project Reactor 的替代品。 Spring MVC 控制器在设计上是阻塞的,这就是为什么它们不能作为挂起函数实现的原因。 https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow