【问题标题】:watchTermination is not triggered in an akka-http flow在 akka-http 流中未触发 watchTermination
【发布时间】:2019-02-04 13:34:15
【问题描述】:

我目前正在尝试构建一个 akka-http websocket 连接,它可以:

  • 向所有连接的客户端广播
  • 回答客户的某些要求

到目前为止,这就是我创建流程的方式:


// keeps a list of all actors so I can broadcast to them
var actors: List[ActorRef] = Nil

private def wsFlow(implicit materializer: ActorMaterializer): Flow[ws.Message, ws.Message, NotUsed] = {
    val (actor, source) = Source.actorRef[String](10, akka.stream.OverflowStrategy.dropTail)
      .toMat(BroadcastHub.sink[String])(Keep.both)
      .run()

    // this never triggers
    source.watchTermination() { (m, f) =>
      f.onComplete(r => println("TERMINATION: " + r.toString))
      actors = actors diff actor :: Nil
      m
    }

    actors = actor :: actors

    val wsHandler: Flow[ws.Message, ws.Message, NotUsed] =
      Flow[ws.Message]
        .merge(source)
        .map {
          case TextMessage.Strict(tm) => handleMessage(actor, tm)
          case _ => TextMessage.Strict("Ignored message!")
        }
    wsHandler
  }

  def broadcast(msg: String): Unit = {
    actors.foreach(_ ! TextMessage.Strict(msg))
  }

我遇到的-希望-最后一个问题是watchTermination 回调永远不会触发(我的控制台上永远不会收到“TERMINATION: ...”消息)。这是为什么?以及如何检测客户何时离开(以便我可以将他从我的actors 列表中删除)?

【问题讨论】:

    标签: scala websocket akka akka-stream akka-http


    【解决方案1】:

    我想出了办法:

    val wsHandler: Flow[ws.Message, ws.Message, NotUsed] = Flow[ws.Message]
      .watchTermination() { (m, f) =>
        f.onComplete(r => {
          println("Client left: " + r.toString)
          actors = actors diff actor :: Nil
          }
        )
        m
      }
      .merge(source)
      .map {
        case TextMessage.Strict(tm) => handleMessage(actor, tm)
        case _ => TextMessage.Strict("Ignored message!")
      }
    

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 2017-07-17
      • 2016-01-12
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多