我在play框架2.6.x中使用websocket尝试了聊天示例。工作正常。现在,对于实际应用程序,我需要根据用户请求创建多个聊天室。用户将可以使用ID或其他内容访问不同的聊天室。我认为这可能与为每个房间创建新流程有关。相关代码在这里:
private val (chatSink, chatSource) = {
val source = MergeHub.source[WSMessage]
.log("source")
.map { msg =>
try {
val json = Json.parse(msg)
inputSanitizer.sanText((json \ "msg").as[String])
} catch {
case e: Exception => println(">>" + msg)
"Malfunction client"
}
}
.recoverWithRetries(-1, { case _: Exception ⇒ Source.empty })
val sink = BroadcastHub.sink[WSMessage]
source.toMat(sink)(Keep.both).run()
}
private val userFlow: Flow[WSMessage, WSMessage, _] = {
Flow.fromSinkAndSource(chatSink, chatSource)
}
但是我真的不知道如何创建带有ID的新流程并在以后访问它。有人可以帮我吗?
答案 0 :(得分:0)
我终于明白了。如果有人遇到类似问题,请在此处发布解决方案。
我的解决方案是使用AsyncCacheApi
通过密钥将Flow
存储在缓存中。必要时生成一个新的Flow
而不是仅创建一个接收器和源:
val chatRoom = cache.get[Flow[WSMessage, WSMessage, _]](s"id=$id")
chatRoom.map{room=>
val flow = if(room.nonEmpty) room.get else createNewFlow
cache.set(s"id=$id", flow)
Right(flow)
}
def createNewFlow: Flow[WSMessage, WSMessage, _] = {
val (chatSink, chatSource) = {
val source = MergeHub.source[WSMessage]
.map { msg =>
try {
inputSanitizer.sanitize(msg)
} catch {
case e: Exception => println(">>" + msg)
"Malfunction client"
}
}
.recoverWithRetries(-1, { case _: Exception ⇒ Source.empty })
val sink = BroadcastHub.sink[WSMessage]
source.toMat(sink)(Keep.both).run()
}
Flow.fromSinkAndSource(chatSink, chatSource)
}