【问题标题】:How this piece of code can be improved and rewritten to kotlin coroutines如何改进这段代码并将其重写为 kotlin 协程
【发布时间】:2021-12-29 08:45:38
【问题描述】:

我正在尝试实现功能:我有一个休息端点,它调用执行可能需要很多时间的代码。我现在改善体验的想法是将那段代码包装为一个新线程,等待完成或某个最大时间过去并返回适当的消息。即使端点已经发回消息,包装代码也应该完成。当前的实现如下所示:

private const val N = 1000
private const val MAX_WAIT_TIME = 5000

@RestController
@RequestMapping("/long")
class SomeController(
    val service: SomeService,
) {
    private val executor = Executors.newFixedThreadPool(N)

    @PostMapping
    fun longEndpoint(@RequestParam("someParam") someParam: Long): ResponseEntity<String> {
        val submit = executor.submit {
            service.longExecution(someParam)
        }
        val start = System.currentTimeMillis()

        while (System.currentTimeMillis() - start < MAX_WAIT_TIME) {
            if (submit.isDone)
                return ResponseEntity.ok("Done")
        }
        return ResponseEntity.ok("Check later")
    }
}

第一个问题是 - 等待时间似乎不对,我们不发布线程,可以改进吗?

更重要的问题 - 如何将其重写为 Kotlin 协程? 我的尝试很简单,任务完成后不返回,看起来像这样:

    @PostMapping
    fun longEndpoint(@RequestParam("someParam") someParam: Long): ResponseEntity<String> = runBlocking {

        val result = async {
            withContext(Dispatchers.Default) {
                service.longExecution(someParam)
            }
        }
        delay(MAX_WAIT_TIME)
        return@runBlocking ResponseEntity.ok(if(result.isCompleted) "Done" else "Check later")
    }

但即使返回了正确的字符串,在longExecution 完成之前不会发送答案。如何解决这个问题,我错过了什么?也许协程在这里是不好的应用程序?

【问题讨论】:

    标签: spring-boot kotlin future kotlin-coroutines coroutine


    【解决方案1】:

    您当前的协程尝试存在几个问题:

    1. 您正在runBlocking 的范围内启动您的async 计算,因此整个端点方法将等待子协程完成,尽管您在此之前尝试过return-ing。
    2. delay() 将始终等待 MAX_WAIT_TIME,即使任务完成得比这更快
    3. (可选)如果您的框架支持异步控制器方法,则根本不必使用runBlocking(Spring WebFlux 确实支持控制器中的suspend 函数)

    对于第一个问题,请记住,每次启动应该比函数寿命更长的协程时,都必须使用外部作用域。 coroutineScope 或 runBlocking 在这些情况下不合适,因为它们会等待您的子协程完成。

    您可以使用CoroutineScope() 工厂函数来创建作用域,但您需要考虑协程的生命周期以及何时取消协程。如果longExecution 函数有错误并且永远挂起,你不想泄漏调用它的协程并炸毁你的内存,所以你应该以某种方式取消这些协程。这就是为什么你应该将作用域作为变量存储在你的类中,并在适当的时候取消它(当你想放弃这些操作时)。

    对于第二个问题,使用withTimeout 很常见,但它不适合您的用例,因为您希望即使在超时等待之后任务也能继续进行。一种可能的解决方案是使用select 子句来等待工作完成,或者等待某个指定的最长时间:

    // TODO call scope.cancel() somewhere appropriate (when this component is not needed anymore)
    val scope = CoroutineScope(Job())
    
    @PostMapping
    fun longEndpoint(@RequestParam("someParam") someParam: Long): ResponseEntity<String> {
        val job = scope.launch {
            longExecution()
        }
        
        val resultText = runBlocking {
            select {
                job.onJoin() { "Done" }
                onTimeout(MAX_WAIT_TIME) { "Check later" } 
            }
        }
        return ResponseEntity.ok(resultText)
    }
    

    注意:我使用的是launch 而不是async,因为您在这里似乎不需要longExecution 的返回值。


    如果您也想解决问题 #3,您可以简单地声明您的处理程序 suspend 并在 select 周围删除 runBlocking:

    // TODO call scope.cancel() somewhere appropriate (when this component is not needed anymore)
    val scope = CoroutineScope(Job())
    
    @PostMapping
    suspend fun longEndpoint(@RequestParam("someParam") someParam: Long): ResponseEntity<String> {
        val job = scope.launch {
            longExecution()
        }
        
        val resultText = select {
            job.onJoin() { "Done" }
            onTimeout(MAX_WAIT_TIME) { "Check later" }
        }
        return ResponseEntity.ok(resultText)
    }
    

    请注意,这需要spring-boot-starter-webflux 而不是spring-boot-starter-web。

    【讨论】:

      【解决方案2】:

      您的实现总是等待 MAX_WAIT_TIME。这可能有效:

      @PostMapping
      fun longEndpoint(@RequestParam("someParam") someParam: Long): ResponseEntity<String> = runBlocking {
      
          try {
              withTimeout(MAX_WAIT_TIME) {
                  async {
                      withContext(Dispatchers.Default) {
                          service.longExecution(someParam)
                      }
                  }
              }
          } catch (ex: CancellationException) {
              return@runBlocking ResponseEntity.ok("Check later")
          }
          return@runBlocking ResponseEntity.ok("Done")
      }
      

      虽然我不确定是否会有任何不需要的副作用,因为这似乎会在协程达到 MAX_WAIT_TIME 时取消。在此处阅读更多信息:
      Cancellation and timeouts

      【讨论】:

      • 问题仍然存在,是runBlocking 块代码在longExecution 完成时完成执行,所以即使通过端点返回“稍后检查”,它仍然比MAX_WAIT_TIME 花费更多的时间
      • @wokstym 嗯,是的,我测试了它,看来你是对的。那不知道怎么弄了,不好意思。希望我能帮忙
      • @wokstym 我编辑了答案。你可以试试这个吗?
      • 还是不行,因为更长的执行结果返回的是“Check later”,但仍然比MAX_WAIT_TIME多得多
      • 请注意longExecution函数没有suspend关键字
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多