现在不推荐Source.actorPublisher
,我想找到一个合适的替代品。
警告:我仍然是Akka newb,试图找到我的路!
基本上我所拥有的是websocket,服务器每秒都会推送一条新消息。
相关代码:
// OLD, deprecated way
//val source: Source[TextMessage.Strict, ActorRef] = Source.actorPublisher[String](Props[KeepAliveActor]).map(i => TextMessage(i))
// NEW way
val sourceGraph: Graph[SourceShape[TextMessage.Strict], NotUsed] = new KeepAliveSource
val source: Source[TextMessage.Strict, NotUsed] = Source.fromGraph(sourceGraph)
val requestHandler: HttpRequest => HttpResponse =
{
case req @ HttpRequest(GET, Uri.Path("/ws"), _, _, _) =>
req.header[UpgradeToWebSocket] match
{
case Some(upgrade) => upgrade.handleMessagesWithSinkSource(Sink.ignore, source)
case None => HttpResponse(400, entity = "Not a valid websocket request")
}
case r: HttpRequest =>
r.discardEntityBytes() // important to drain incoming HTTP Entity stream
HttpResponse(404, entity = "Unknown resource!")
}
老演员:(基本上取自:Actorpublisher as source in handleMessagesWithSinkSource)
case class KeepAlive()
class KeepAliveActor extends ActorPublisher[String]
{
import scala.concurrent.duration._
implicit val ec = context.dispatcher
val tick = context.system.scheduler.schedule(1 second, 1 second, self, KeepAlive())
var cnt = 0
var buffer = Vector.empty[String]
override def receive: Receive =
{
case KeepAlive() =>
{
cnt = cnt + 1
if (buffer.isEmpty && totalDemand > 0)
{
onNext(s"${cnt}th Message from server!")
}
else {
buffer :+= cnt.toString
if (totalDemand > 0) {
val (use,keep) = buffer.splitAt(totalDemand.toInt)
buffer = keep
use foreach onNext
}
}
}
}
override def postStop() = tick.cancel()
}
古老的方式就像一个魅力。
现在新代码基于GraphStage
class KeepAliveSource extends GraphStage[SourceShape[TextMessage.Strict]]
{
import scala.concurrent.duration._
override def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
{
new TimerGraphStageLogic(shape)
{
// All state MUST be inside the GraphStageLogic,
// never inside the enclosing GraphStage.
// This state is safe to access and modify from all the
// callbacks that are provided by GraphStageLogic and the
// registered handlers.
private var counter = 1
setHandler(out, new OutHandler
{
override def onPull(): Unit =
{
push(out, TextMessage(counter.toString))
counter += 1
schedulePeriodically(None, 1 second)
}
})
}
}
val out: Outlet[TextMessage.Strict] = Outlet("KeepAliveSource")
override def shape: SourceShape[TextMessage.Strict] = SourceShape(out)
}
无论出于何种原因,这仍然让我感到困惑,尽管我假设schedulePeriodically(None, 1 second)
会在每条消息之间增加1秒的延迟。我显然是错的。
增加此值并不会改变我的糟糕浏览器无法处理请求和崩溃的事实(我可以在simple websocket client
的日志中看到它)
答案 0 :(得分:1)
schedulePeriodically
调用不会影响您的舞台的行为。每当下游阶段请求消息时,都会调用onPull
处理程序,并且会立即发送消息push
。这就是为什么你看不到任何限制。
尽管GraphStage
DSL(您选择的那个)非常灵活,但也很难做到正确。对于像这样的简单任务,最好利用Akka提供的更高级别的阶段。与Source.tick
(docs)相似。
val tickingSource: Source[String, Cancellable] =
Source.tick(initialDelay = 1.second, interval = 5.seconds, tick = "hello")
在您的示例中,您需要一个递增的计数器才能发布,因此您可以将更多逻辑附加到滴答源,例如
val tickingSource: Source[Strict, Cancellable] =
Source.tick(initialDelay = 1.second, interval = 5.seconds, tick = NotUsed)
.zipWithIndex
.map{ case (_, counter) ⇒ TextMessage(counter.toString) }
如果您对基础GraphStage
的工作方式感兴趣,可以随时查看TickSource
代码本身(请参阅github)。
主要区别在于TickSource
在push
回调中调用onTimer
(来自TimerGraphStageLogic
,您可以覆盖)。