- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
设置如下:我希望能够通过 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/
我正在尝试使用 Scala 2.12.3、sbt 0.13.6 以及 build.sbt 文件中的以下库依赖项构建一个项目: libraryDependencies ++= Seq( "com.t
我根本没有任何 Akka 经验。我想知道 Akka 消息传递如何在 JVM 内以及 JVM 之间工作。 JVM 中的消息是一些类似 POJO 的对象吗? JVM之间的通信是否需要任何类型的JMS(如服
Akka的EventBus是否可以与远程 Actor 一起使用? 据我所知,它本身不支持此功能。任何人都可以确认吗? 看起来有可能对提供相似功能的Actor进行编码。例如。在订阅远程服务器上的Even
我在单个 JVM 上使用 Akka 开发了我的应用程序。现在我想在多台机器上分配工作负载。我开始阅读文档并感到困惑。 有两种方法可以通过集群和远程处理使 Akka 应用程序分发。 我不明白两者之间的区
我想使用 Akka HTTP 构建一个连接到现有接收器(带有 Kafka react 流)的 REST 服务,但我不知道如何将 HTTP 流链接到 Akka 流接收器... 我应该选择使用 Flows
我在某处听说默认情况下是一个 Actor 系统,这意味着它的 ExecutorService/Dispatcher 正在创建一个非 Deamon 线程池来运行 Actor。如果确实如此,那将解释我所经
在我的应用程序中,我有一个角色需要在等待某些操作完成时存储消息,同时它需要支持高优先级消息(控制消息)。 stash trait 需要一个 Dequeue邮箱类型,我找不到控制感知出队邮箱是否有意义。
Akka.NET 和原始 Akka 可以使用 Remoting 进行通信吗? 换句话说,Akka 可以用于连接系统中的 JVM 和 CLR 吗? 最佳答案 这个问题在 akka.net Github
Akka 新手。创建一个扩展 SupervisorStrategy 的新 Scala 类为我提供了以下模板: class MySupervisorStrategy extends Supervisor
我正在尝试为包含并行处理流的 Akka 流定义一个图(我正在使用 Akka.NET,但这应该无关紧要)。想象一个订单的数据源,每个订单由一个订单 ID 和一个产品列表(订单商品)组成。工作流程如下:
我有一个 akka actor(worker)接收请求并回复它。请求处理可能需要 3-60 分钟。来电者(也是 Actor )目前正在使用 !!!并等待 future.get,但是如果需要,可以更改
我应该如何在 Akka 持久化 (Eventsourcing/CQRS) 中构建我的 Actor? 分层 平行 我的电子商务应用程序中有这些域对象 用户 - 用户可以创建帐户 商店 - 用户可以创建商
我正在尝试构建和运行一个 akka 流(在 Java DSL 中),以 2 个 actor 作为源,然后是一个合并结点,然后是 1 个接收器: Source src1 = Source.act
我正在尝试监督 Akka Actor ,更具体地说是 Cluster Singleton创建使用 ClusterSingletonManager .我试图更好地控制异常、日志和 Actor 的生命周期
我试图了解何时何地使用不同的 built-in Akka mailboxes以及何时适合自己滚动。但是,该页面上的任何地方都没有解释“ 有界邮箱 ”实际上是什么,或者它的行为方式与无界邮箱有何不同。此
在Akka中等待多个actor的结果的正确方法是什么? Principles of Reactive Programming Coursera 类(class)有一个带有复制键值存储的练习。无需深入研
我正在为一个项目评估 Akka,我正在尝试弄清楚我是否可以通过将参与者状态保存在高可用数据存储中来使用 Akka-Persistence 实现服务的高可用性。 (我不打算使用 Akka-Cluster
我阅读了 Akka 文档并找到了这个 As mentioned before, if a node is unreachable then gossip convergence is not poss
我正在使用 akka 流,并且我有一段我需要有条件地跳过的图表,因为流程无法处理某些值。具体来说,我有一个接受字符串并发出 http 请求的流,但是当字符串为空时,服务器无法处理这种情况。但我只需要返
我们正在考虑使用 Akka 进行客户端服务器通信,并尝试对数据传输进行基准测试。目前我们正在尝试发送一百万条消息,其中每条消息都是一个具有 8 个字符串字段的案例类。 目前,我们正在努力获得可接受的性
我是一名优秀的程序员,十分优秀!