9

我使用 Finagle 作为 Web 服务器,我想从我的应用程序逻辑中返回 Scala-Futures。如何以非阻塞方式将 scala.concurrent.Future 转换为 com.twitter.util.Future?

4

3 回答 3

21

没有足够的环境来测试这个,但这是我写的"com.twitter" %% "finagle-http" % "6.25.0"

import com.twitter.{util => twitter}
import scala.concurrent.{ExecutionContext, Promise, Future}
import scala.util.{Failure, Success, Try}
import language.implicitConversions

object TwitterConverters {
  implicit def scalaToTwitterTry[T](t: Try[T]): twitter.Try[T] = t match {
    case Success(r) => twitter.Return(r)
    case Failure(ex) => twitter.Throw(ex)
  }

  implicit def twitterToScalaTry[T](t: twitter.Try[T]): Try[T] = t match {
    case twitter.Return(r) => Success(r)
    case twitter.Throw(ex) => Failure(ex)
  }

  implicit def scalaToTwitterFuture[T](f: Future[T])(implicit ec: ExecutionContext): twitter.Future[T] = {
    val promise = twitter.Promise[T]()
    f.onComplete(promise update _)
    promise
  }

  implicit def twitterToScalaFuture[T](f: twitter.Future[T]): Future[T] = {
    val promise = Promise[T]()
    f.respond(promise complete _)
    promise.future
  }
}
于 2015-05-19T06:45:00.463 回答
15

也可以使用 Twitter bijections 库:https ://github.com/twitter/bijection

com.twitter.bijection.twitter_util.UtilBijectionshttps://github.com/twitter/bijection/blob/develop/bijection-util/src/main/scala/com/twitter/bijection/twitter_util/UtilBijections.scala

这个库处理重要的细节,例如,如果你来回转换对象,它只是解开原始对象。

于 2015-05-20T15:29:15.253 回答
8

这是使用 twitter 双射库的示例:

import scala.concurrent.{Future => ScalaFuture}
import com.twitter.util.{Future => TwitterFuture}

// extend values by adding the conversion method "as"
import com.twitter.bijection.Conversion.asMethod

// pull in various implicit converters that "as" expects, 
// including twitter2ScalaFuture:
import com.twitter.bijection.twitter_util.UtilBijections._

def doSomething: ScalaFuture[T] = {
    val response: TwitterFuture[T] = ???
    response.as[ScalaFuture[T]]
}
于 2016-09-01T19:45:26.600 回答