Akka:动态地将Actors添加到BroadcastRouter

时间:2012-11-12 14:08:28

标签: java events akka actor

让Broadcast actor随时间动态添加/删除路由的正确方法是什么?

问题的背景: 演员听取特定物品的价格变化,然后向所有其他演员(路线)广播价格变化,并根据内部规则行事(例如,如果价格是X买入或卖出)。

我是Akka的新手,但在阅读了documentation后,我相信我已经找到了所需的组件,但如果您觉得我的设计或组件使用不正确,请发表评论/回答。

我想从固定的路线列表中更改

        ActorRef actor1 = system.actorOf(new Props(LimitOrderActor.class));
        ActorRef actor2 = system.actorOf(new Props(LimitOrderActor.class));
        ActorRef actor3 = system.actorOf(new Props(LimitOrderActor.class));
        Iterable<ActorRef> routees = Arrays.asList(new ActorRef[] { actor1, actor2, actor3 });
        ActorRef actorBroadcastRouter1 = system.actorOf(new Props(TickerWatcherActor.class).withRouter(BroadcastRouter.create(routees)), "router1");

类似于动态大小的BroadcastRouter,其中在BroadcastRouter启动并运行后创建了actor

        int lowerBound = 1;
        int upperBound = 10000;
        DefaultResizer resizer = new DefaultResizer(lowerBound, upperBound);
        BroadcastRouter broadcastRouter2 = new BroadcastRouter(resizer);
        ActorRef actorBroadcastRouter2 = system.actorOf(new Props(TickerWatcherActor.class).withRouter(broadcastRouter2), "router2");

        ActorRef actor4 = system.actorOf(new Props(LimitOrderActor.class).withRouter((RouterConfig) broadcastRouter2));
        ActorRef actor5 = system.actorOf(new Props(LimitOrderActor.class).withRouter((RouterConfig) broadcastRouter2));
        ActorRef actor6 = system.actorOf(new Props(LimitOrderActor.class).withRouter((RouterConfig) broadcastRouter2));

现在,Actor“actorBroadcastRouter2”正在接收消息而不是预期的LimitOrderActor actor 4,5和6.我做错了什么?

编辑:我相信现在我要找的是Event Bus而不是BroadcastRouter

   final ActorRef actor = system.actorOf(new Props(LimitOrderActor.class));
   system.eventStream().subscribe(actor, String.class);

2 个答案:

答案 0 :(得分:0)

让我们关闭这个问题,我在同一个问题上磕磕绊绊。这不是广播路由器工作的方式。您可以在actor4actor5actor6中创建新的广播路由器,而不是添加到actorBroadcastRouter2中的现有广播路由器。

你想要的是scala中的一个非常简单的监听器特性,这在使用Java编程Akka时很遗憾:

class MyActor extends Actor with Listeners {
  def receive = {
     case yourmessages => gossip("To All my listeners")
  } orElse listenerManagement
}

val myActor = context.actorOf(Props[MyActor])

myActor ! Listen(someActorRef)

myActor ! "pigdog"

必须使用自己的Java版本或使用DistributedPubSubExtension来获得更全面的内容。

https://groups.google.com/forum/?fromgroups=#!topic/akka-user/NEOY9IxRW5I

https://github.com/akka/akka/blob/master/akka-actor/src/main/scala/akka/routing/Listeners.scala

http://doc.akka.io/docs/akka/snapshot/contrib/distributed-pub-sub.html#a-small-example-in-java

答案 1 :(得分:0)

使用事件总线而不是BroadcastRouter:

final ActorRef actor = system.actorOf(new Props(LimitOrderActor.class));
system.eventStream().subscribe(actor, String.class);