【问题标题】:Optimisation with coroutine使用协程进行优化
【发布时间】:2020-10-26 16:20:44
【问题描述】:

我在 Kotlin 中有简单的代码,它使用 okhttp lib 列出了请求 (150),并且我使用 JSOUp 解析了每个 html 结果。

我用的是协程但是不懂,有没有协程的时间都是一样的(23秒)

也许我做了坏事?还是http请求受限?

我的代码:

fun parse(list: ArrayList<ChampionBean>) {

    runBlocking {
        list.forEach {
            launch {
                   val response = requestWithOkhttp(it.url)
                   val doc = Jsoup.parse(response.body?.string())
                   response.close()
                   parsedocwithJsoup(doc, it)                 
            }
        }
    }
}

【问题讨论】:

  • 几件事。您在那里的协程将继承上下文,因此您可能有一个只有 1 个线程的上下文。您可以打印println("I'm working in thread ${Thread.currentThread().name}") 来查找线程名称。另外 okhttpclient 是如何配置的?因为它可以配置为只使用一个 http 连接。
  • 感谢您的回答@Augusto,我所有的发布都在同一个线程上。我用启动解决了我的问题(Dispatchers.Default)
  • @Tenfour04 这是一个脚本,目的是等待所有请求完成。 runblocking 的主要作用是等待内部的所有启动/异步

标签: kotlin kotlin-coroutines coroutine


【解决方案1】:

我只需添加 Dispatchers.Default 即可。 7 秒而不是 23 秒。 我不知道为什么,默认调度程序不是默认调度程序。 代码在 Intellij 的 main 方法中运行,没有 UI

 fun parse(list: ArrayList<ChampionBean>) {
    
        runBlocking {
            list.forEach {
                launch(Dispatchers.Default) {
                       val response = requestWithOkhttp(it.url)
                       val doc = Jsoup.parse(response.body?.string())
                       response.close()
                       parsedocwithJsoup(doc, it)                 
                }
            }
        }
    } 

【讨论】:

  • 而 Dispatchers.IO 同时请求太多,所以服务器停止应答
猜你喜欢
  • 1970-01-01
  • 2021-07-17
  • 2017-05-27
  • 2015-08-01
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多