gpt4 book ai didi

scala - 如何在 scalaz 任务中关闭 AsyncHttpClient

转载 作者:行者123 更新时间:2023-12-02 09:28:24 26 4
gpt4 key购买 nike

我正在尝试将 AsyncHttpClient 和 Scalaz Task 结合在一起。通常,如果我使用 AsyncHttpClient,我可以调用 client.close 来停止客户端。

val asyncHttpClient = new AsyncHttpClient()
println(asyncHttpClient.prepareGet("http://www.google.com"))

asyncHttpClient.close()

因此电流将停止。但是,如果我将 api 调用包装到 Task.我不知道如何阻止它。

  def get(s: String) = Task.async[Int](k => {
asyncHttpClient.prepareGet(s).execute(toHandler)
Thread.sleep(5000)
asyncHttpClient.closeAsynchronously()
} )

def toHandler[A] = new AsyncCompletionHandler[Response] {
def onCompleted(r: Response) = {
println("get response ", r.getResponseBody)
r
}
def onError(e: Throwable) = {
println("some error")
e
}
}

println(get("http://www.google.com").run)

当前进程仍在运行。我认为原因是 Task 和 AsynClient 都是异步的。我不知道我应该做什么来关闭它

提前非常感谢

最佳答案

问题在于 Task.async 采用可以注册回调的函数。这有点令人困惑,而且类型并没有多大帮助,因为里面有太多该死的 Unit ,但这意味着你想要更多类似这样的东西:

import com.ning.http.client._
import scalaz.syntax.either._
import scalaz.concurrent.Task

val asyncHttpClient = new AsyncHttpClient()

def get(s: String): Task[Response] = Task.async[Response](callback =>
asyncHttpClient.prepareGet(s).execute(
new AsyncCompletionHandler[Unit] {
def onCompleted(r: Response): Unit = callback(r.right)
def onError(e: Throwable): Unit = callback(e.left)
}
)
)

这并不处理关闭客户端——它只是为了展示总体思路。您可以在处理程序中关闭客户端,但我建议更像这样:

import com.ning.http.client._
import scalaz.syntax.either._
import scalaz.concurrent.Task

def get(client: AsyncHttpClient)(s: String): Task[Response] =
Task.async[Response](callback =>
client.prepareGet(s).execute(
new AsyncCompletionHandler[Unit] {
def onCompleted(r: Response): Unit = callback(r.right)
def onError(e: Throwable): Unit = callback(e.left)
}
)
)

def initClient: Task[AsyncHttpClient] = Task(new AsyncHttpClient())
def closeClient(client: AsyncHttpClient): Task[Unit] = Task(client.close())

然后:

val res = for {
c <- initClient
r <- get(c)("http://www.google.com")
_ <- closeClient(c)
} yield r

res.unsafePerformAsync(
_.fold(
_ => println("some error"),
r => println("get response " + r.getResponseBody)
)
)

这避免了 closeAsynchronously (无论如何,这似乎是 going away )。

关于scala - 如何在 scalaz 任务中关闭 AsyncHttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35590978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com