如何关闭Finagle Thrift客户端?

Chr*_*rle 3 scala thrift finagle scrooge

我正在使用scrooge + thrift来生成我的服务器和客户端代码.到目前为止一切正常.

这是我如何使用客户端的简化示例:

private lazy val client =
  Thrift.newIface[MyPingService[Future]](s"$host:$port")

def main(args: Array[String]): Unit = {
  logger.info("ping!")
  client.ping().foreach { _ =>
    logger.info("pong!")
    // TODO: close client
    sys.exit(0)
  }
}
Run Code Online (Sandbox Code Playgroud)

一切都工作正常,但服务器抱怨程序退出未关闭的连接.我看了一遍,但我似乎无法弄清楚如何关闭client实例.

所以我的问题是,你如何关闭Finagle的节俭客户?我觉得我错过了一些明显的东西.

j3h*_*j3h 7

据我所知,当您使用自动Thrift.newIface[Iface]方法创建服务时,您无法关闭它,因为您的代码唯一知道的结果值是它符合Iface.如果需要关闭它,可以分两步实例化客户端,在一个中创建Thrift服务,在另一个中将其调整到您的界面.

以下是您使用Scrooge生成Thrift界面的样子:

val serviceFactory: ServiceFactory[ThriftClientRequest,Array[Byte]] =
  Thrift.newClient(s"$host:$port")

val client: MyPingService[Future] =
  new MyPingService.FinagledClient(serviceFactory.toService)

doStuff(client).ensure(serviceFactory.close())
Run Code Online (Sandbox Code Playgroud)

我在repl中尝试了这个,它对我有用.这是一个轻微编辑的成绩单:

scala> val serviceFactory = Thrift.newClient(...)
serviceFactory: ServiceFactory[ThriftClientRequest,Array[Byte]] = <function1>

scala> val tweetService = new TweetService.FinagledClient(serviceFactory.toService)
tweetService: TweetService.FinagledClient = TweetService$FinagledClient@20ef6b76

scala> Await.result(tweetService.getTweets(GetTweetsRequest(Seq(20))))
res7: Seq[GetTweetResult] = ... "just setting up my twttr" ...

scala> serviceFactory.close
res8: Future[Unit] = ConstFuture(Return(()))

scala> Await.result(tweetService.getTweets(GetTweetsRequest(Seq(20))))
com.twitter.finagle.ServiceClosedException
Run Code Online (Sandbox Code Playgroud)

这不是太糟糕,但我希望有一种更好的方式,我还不知道.