如何通过使用Akka流来重构此代码. [英] How to refactor this code by using akka streams.

查看:69
本文介绍了如何通过使用Akka流来重构此代码.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个想法是让频道保持打开状态,以便以后使用.在playframework 2.5.x中,文档指出您必须使用akka流,但没有说明如何实现此示例.有人可以帮助我吗?

The idea is to keep the channel opened to use it later. In playframework 2.5.x the documentation says that you have to use akka streams but does not say anything how to achieve this example. Somebody can help me?

import play.api.mvc._
import play.api.libs.iteratee._
import play.api.libs.concurrent.Execution.Implicits.defaultContext

def socket =  WebSocket.using[String] { request =>

  // Concurrent.broadcast returns (Enumerator, Concurrent.Channel)
  val (out, channel) = Concurrent.broadcast[String]

  // log the message to stdout and send response back to client
  val in = Iteratee.foreach[String] {
    msg => println(msg)
      // the Enumerator returned by Concurrent.broadcast subscribes to the channel and will
      // receive the pushed messages
      channel push("I received your message: " + msg)
  }
  (in,out)
}

推荐答案

您将必须执行以下操作!

You'll have to do something like this!

val (subscriber, publisher)=Source.asSubscriber[String]
      .toMat(Sink.asPublisher[String](fanout = true))(Keep.both).run()

def websocketAction=WebSocket.accept { requestHeader =>
    Flow.fromSinkAndSource(Sink.fromSubscriber(subscriber),Source.fromPublisher(publisher))
}

在给定接收器和流的情况下,第一部分将创建推送消息并接收消息(订阅发布者)所需的对象.

The first part will create, given a sink and a flow, the objects that you'll need to push messages and receive them (subscribe to the publisher).

最后,您将使用代码Flow.fromSinkAndSource为收到的每个Websocket请求创建一个流程...关于Akka流(Source s,Sink s和Flow s)尚不清楚的是它们代表流的形状,但不代表流本身的形状...当您实现它们时(使用方法runWithrun),流就去了.现在...使用WebSockets时,播放会收到Source(使用服务器发送事件时)或Flow.而且它们仍未实现...因此您需要实现它们(第一行),然后再创建一个流程! (websocketAction行)

finally you'll create a flow for every websocket request you receive with that code Flow.fromSinkAndSource... Something that's not clear regarding Akka Streams (Sources, Sinks and Flows) is that they represent the shape of the flow, but not the flow per se... the flow goes when you materialize them (with method runWith or run). Now... Play receives either Sources (when using Server Sent Events) or Flows when using WebSockets. And they are not still materialized... so you need to materialize them (the first line) and then creating a Flow AGAIN! (the websocketAction line)

很抱歉,如果我不够清楚,但是使用该代码,它将可以正常工作.

I'm sorry if I'm not clear enough, however use that code, it will work.

这篇关于如何通过使用Akka流来重构此代码.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆