【发布时间】:2019-03-06 06:35:45
【问题描述】:
我们需要为以下用例实现服务器发送事件:
- 在服务器上进行一些处理后向 UI 发送通知。这个处理是基于一些逻辑的
- 从 RabbitMQ 读取消息并对其执行一些操作后向 UI 发送通知。
我们使用 Scala(2.11/2.12) 和 Play framework(2.6.x) 的技术集。 库:akka.stream.scaladsl.Source
我们从以下示例 https://github.com/playframework/play-scala-streaming-example 开始我们的概念证明,然后我们通过创建不同的源进行扩展。 我们尝试使用 Source.apply,soure.single 创建源代码。
但是,一旦源中的所有元素都被推送到 UI,我的事件流就关闭了。但我不希望事件流关闭。另外我不想使用一些计时器(Source.tick)或Source.repeat。
创建我的源时,集合假设有一些 x 元素,然后服务添加了 4 个元素。但是在 x 个元素之后,事件流被关闭,然后再次重新打开。
有什么方法可以让我的事件流是无限的并且只有我的会话被注销或者我们可以明确地关闭它才会关闭。
//KeepAlive 的代码(在 cmets 中询问)
object NotficationUtil {
var userNotificationMap = Map[Integer, Queue[String]]()
def addUserNotification(userId: Integer, message: String) = {
var queue = userNotificationMap.getOrElse(userId, Queue[String]())
queue += message
userNotificationMap.put(userId, queue)
}
def pushNotification(userId: Integer): Source[JsValue, _] = {
var queue = userNotificationMap.getOrElse(userId, Queue[String]())
Source.single(Json.toJson(queue.dequeueAll { x => true }))
}
}
@Singleton
class EventSourceController @Inject() (cc: ControllerComponents) extends AbstractController(cc) with FlowFactory{
def pushNotifications(user_id:Integer) = Action {
val stream = NotficationUtil.pushNotification(user_id)
Ok.chunked(stream.keepAlive(50.second, ()=>Json.obj("data"->"heartbeat")) via EventSource.flow).as(ContentTypes.EVENT_STREAM)
}
}
【问题讨论】:
标签: scala akka-stream server-sent-events playframework-2.6