我正在尝试将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都是异步的。我不知道该怎么做才能关闭它
非常感谢提前
答案 0 :(得分:5)
问题是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。)