我有以下无法编译的代码段:
import akka.actor.ActorSystem
import akka.Done
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.ws._
import scala.concurrent._
import scala.concurrent.duration._
object Main extends App {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
import system.dispatcher
// Future[Done] is the materialized value of Sink.foreach,
// emitted when the stream completes
val incoming: Sink[Message, Future[Done]] =
Sink.foreach[Message] {
case message: TextMessage.Strict =>
println(message.text)
}
// flow to use (note: not re-usable!)
val sourceSocketFlow = RestartSource.withBackoff(
minBackoff = 3.seconds,
maxBackoff = 30.seconds,
randomFactor = 0.2,
maxRestarts = 3
) { () =>
Source.tick(2.seconds, 2.seconds, TextMessage("Hello world!!!"))
.viaMat(Http().webSocketClientFlow(WebSocketRequest("ws://127.0.0.1:8080/")))(Keep.right)
}
// the materialized value is a tuple with
// upgradeResponse is a Future[WebSocketUpgradeResponse] that
// completes or fails when the connection succeeds or fails
// and closed is a Future[Done] with the stream completion from the incoming sink
val (upgradeResponse, closed) =
sourceSocketFlow
.toMat(incoming)(Keep.both) // also keep the Future[Done]
.run()
// just like a regular http request we can access response status which is available via upgrade.response.status
// status code 101 (Switching Protocols) indicates that server support WebSockets
val connected = upgradeResponse.flatMap { upgrade =>
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
Future.successful(Done)
} else {
throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
}
}
connected.onComplete(println)
closed.foreach(_ => println("closed"))
}
这里的问题是:
// the materialized value is a tuple with
// upgradeResponse is a Future[WebSocketUpgradeResponse] that
// completes or fails when the connection succeeds or fails
// and closed is a Future[Done] with the stream completion from the incoming sink
val (upgradeResponse, closed) =
sourceSocketFlow
.toMat(incoming)(Keep.both) // also keep the Future[Done]
.run()
不在元组的第一个位置返回Future[WebSocketUpgradeResponse]
,而是返回NotUsed
。
问题是,如何获取返回类型Future[WebSocketUpgradeResponse]
来确定连接是否成功。
答案 0 :(得分:2)
RestartSource#withBackoff接受类型为sourceFactory
的{{1}}并返回类型为() => Source[T, _]
的新源。因此,不可能从包装的源中提取物化值。这可能是因为在每次RestartSource重新启动时,物化值都会有所不同。
问题是,如何获取返回类型Future [WebSocketUpgradeResponse]来确定连接成功。
如果要检查是否已建立连接,并且WebSockets握手是否成功,则可以使用Source#preMaterialize预先实现源。经过稍微修改的代码版本如下所示:
Source[T, NotUsed]
如果连接失败或websocket handshake fails,则无需执行任何操作。这两种情况都将由RestartSource处理。