scala - akka 通过 tcp 传输

标签 scala tcp akka akka-stream

设置如下:我希望能够通过 tcp 连接将消息(json 转换为字节串)从发布者流式传输到远程服务器订阅者。
理想情况下,发布者应该是接收内部消息、将它们排队然后将它们流式传输到订阅者服务器的角色,当然如果有突出的需求。我知道这样做的必要条件是扩展 ActorPublisher 类,以便在需要时 onNext() 消息。
我的问题是,到目前为止,我只能向服务器发送(正确接收和解码)一次 消息,每次都打开一个新连接。我没有设法理解 akka 文档,也无法使用 ActorPublisher 设置正确的 tcp Flow
这是发布者的代码:

def send(message: Message): Unit = {
    val system = Akka.system()
    implicit val sys = system

    import system.dispatcher

    implicit val materializer = ActorMaterializer()

    val address =     Play.current.configuration.getString("eventservice.location").getOrElse("localhost")
    val port = Play.current.configuration.getInt("eventservice.port").getOrElse(9000)

    /*** Try with actorPublisher ***/
    //val result = Source.actorPublisher[Message]    (Props[EventActor]).via(Flow[Message].map(Json.toJson(_).toString.map(ByteString(_))))

    /*** Try with actorRef ***/
    /*val source = Source.actorRef[Message](0, OverflowStrategy.fail).map(
  m => {
    Logger.info(s"Sending message: ${m.toString}")
    ByteString(Json.toJson(m).toString)
  }
)
    val ref = Flow[ByteString].via(Tcp().outgoingConnection(address, port)).to(Sink.ignore).runWith(source)*/

    val result = Source(Json.toJson(message).toString.map(ByteString(_))).
  via(Tcp().outgoingConnection(address, port)).
  runFold(ByteString.empty) { (acc, in) ⇒ acc ++ in }//Handle the future
}

最后是相当标准的 Actor 代码:

import akka.actor.Actor
import akka.stream.actor.ActorSubscriberMessage.{OnComplete, OnError}
import akka.stream.actor.{ActorPublisherMessage, ActorPublisher}

import models.events.Message

import play.api.Logger

import scala.collection.mutable

class EventActor extends Actor with ActorPublisher[Message] {
   import ActorPublisherMessage._
   var queue: mutable.Queue[Message] = mutable.Queue.empty

   def receive = {
      case m: Message =>
         Logger.info(s"EventActor - message received and queued: ${m.toString}")
         queue.enqueue(m)
         publish()

      case Request => publish()

      case Cancel =>
          Logger.info("EventActor - cancel message received")
          context.stop(self)

      case OnError(err: Exception) =>
          Logger.info("EventActor - error message received")
          onError(err)
          context.stop(self)

      case OnComplete =>
          Logger.info("EventActor - onComplete message received")
          onComplete()
          context.stop(self)
   }

    def publish() = {
     while (queue.nonEmpty && isActive && totalDemand > 0) {
     Logger.info("EventActor - message published")
     onNext(queue.dequeue())
   }
 }

如有必要,我可以提供订阅者的代码:

def connect(system: ActorSystem, address: String, port: Int): Unit = {
implicit val sys = system
import system.dispatcher
implicit val materializer = ActorMaterializer()

val handler = Sink.foreach[Tcp.IncomingConnection] { conn =>
  Logger.info("Event server connected to: " + conn.remoteAddress)
  // Get the ByteString flow and reconstruct the msg for handling and then output it back
  // that is how handleWith work apparently
  conn.handleWith(
    Flow[ByteString].fold(ByteString.empty)((acc, b) => acc ++ b).
      map(b => handleIncomingMessages(system, b.utf8String)).
      map(ByteString(_))
  )
}

val connections = Tcp().bind(address, port)
val binding = connections.to(handler).run()

binding.onComplete {
  case Success(b) =>
    Logger.info("Event server started, listening on: " + b.localAddress)
  case Failure(e) =>
    Logger.info(s"Event server could not bind to $address:$port: ${e.getMessage}")
    system.terminate()
}
}

提前感谢您的提示。

最佳答案

我的第一个建议是不要编写自己的队列逻辑。 Akka 提供了这个开箱即用的功能。您也不需要编写自己的 Actor,Akka Streams 也可以提供。

首先,我们可以创建 Flow,通过 Tcp 将您的发布者连接到您的订阅者。在您的发布者代码中,您只需创建一次 ActorSystem 并连接到外部服务器一次:

//this code is at top level of your application

implicit val actorSystem = ActorSystem()
implicit val actorMaterializer = ActorMaterializer()
import actorSystem.dispatcher

val host = Play.current.configuration.getString("eventservice.location").getOrElse("localhost")
val port    = Play.current.configuration.getInt("eventservice.port").getOrElse(9000)

val publishFlow = Tcp().outgoingConnection(host, port)

publishFlow 是一个 Flow将输入要发送给外部订阅者的 ByteString 数据,并输出来自订阅者的 ByteString 数据:

//  data to subscriber ----> publishFlow ----> data returned from subscriber

下一步是发布者来源。您可以使用 Source.actorRef 而不是编写自己的 Actor。至 "materialize" Stream 到 ActorRef。本质上,Stream 将成为我们稍后使用的 ActorRef:

//these values control the buffer
val bufferSize = 1024
val overflowStrategy = akka.stream.OverflowStrategy.dropHead

val messageSource = Source.actorRef[Message](bufferSize, overflowStrategy)

我们还需要一个 Flow 来将 Messages 转换成 ByteString

val marshalFlow = 
  Flow[Message].map(message => ByteString(Json.toJson(message).toString))

最后我们可以连接所有的部分。由于您没有收到来自外部订阅者的任何数据,我们将忽略来自连接的任何数据:

val subscriberRef : ActorRef = messageSource.via(marshalFlow)
                                            .via(publishFlow)
                                            .runWith(Sink.ignore)     

我们现在可以把这个流当作一个 Actor 来对待:

val message1 : Message = ???

subscriberRef ! message1

val message2 : Message = ???

subscriberRef ! message2

关于scala - akka 通过 tcp 传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35830401/

相关文章:

akka - Akka Actor 执行是否互斥?

java - 在 Akka 中初始化一个 actor,Play 2.4.2

scala - 当对中的顺序不相关时,获取 RDD 中对的唯一值

scala - 在不使用 Try/Catch block 的情况下如何编写此代码?

c# - 关闭外部 TCP 连接

linux - 无法关闭已建立的数据库连接

vb.net - 每个 TcpClients 发送和接收位图

scala - 用于理解的产量会引发类型不匹配的编译器错误

scala - 得到 NoClassDefFound 运行示例代码

java - 在 Akka 中记录收到的消息