【发布时间】:2016-04-01 04:25:56
【问题描述】:
我正在尝试使用 reactive-kafka、akka-http 和 akka-stream 编写一个 Kafka 消费者到 websocket 流。
val publisherActor = actorSystem.actorOf(CommandPublisher.props)
val publisher = ActorPublisher[String](publisherActor)
val commandSource = Source.fromPublisher(publisher) map toMessage
def toMessage(c: String): Message = TextMessage.Strict(c)
class CommandPublisher extends ActorPublisher[String] {
override def receive = {
case cmd: String =>
if (isActive && totalDemand > 0)
onNext(cmd)
}
}
object CommandPublisher {
def props: Props = Props(new CommandPublisher())
}
// This is the route
def mainFlow(): Route = {
path("ws" / "commands" ) {
handleWebSocketMessages(Flow.fromSinkAndSource(Sink.ignore, commandSource))
}
}
从 kafka 消费者(这里省略),我做了一个publisherActor ! commandString 来动态添加内容到 websocket。
但是,当我启动多个客户端到 websocket 时,我在后端遇到了这个异常:
[ERROR] [03/31/2016 21:17:10.335] [KafkaWs-akka.actor.default-dispatcher-3][akka.actor.ActorSystemImpl(KafkaWs)] WebSocket handler failed with can not subscribe the same subscriber multiple times (see reactive-streams specification, rules 1.10 and 2.12)
java.lang.IllegalStateException: can not subscribe the same subscriber multiple times (see reactive-streams specification, rules 1.10 and 2.12)
at akka.stream.impl.ReactiveStreamsCompliance$.canNotSubscribeTheSameSubscriberMultipleTimesException(ReactiveStreamsCompliance.scala:35)
at akka.stream.actor.ActorPublisher$class.aroundReceive(ActorPublisher.scala:295)
...
一个流不能用于所有 websocket 客户端吗?还是应该为每个客户端创建流/发布者角色?
在这里,我打算向所有 websocket 客户端发送“当前”/“实时”通知。通知历史无关紧要,新客户需要忽略。
【问题讨论】:
标签: websocket akka-stream akka-http