Akka(java),非阻止广播给所有孩子 [英] Akka (java), non blocking broadcast to all children
问题描述
假设我有一个地区演员,每个地区都有一定数量的人。你如何向每个人广播一条消息,知道人们的名单可以随着时间的推移而改变,广播路由器似乎是选择,但问题是他们有最大数量的路由,而且我不能动态地将人们附加到一个路由器。
Let's say I have a Region Actor, and each region has a certain number of people inside it. How do you broadcast a message to everyone, knowing that the list of people can change over time, broadcast routers seems to be the choice, but then the problem is that they have a maximum number of routees, and that I cannot dynamically append people to a router.
我的问题是:我知道有一个EventBus,我可以订阅我的人员到活动总线,但我不希望他们接收发布的每条消息,我希望他们收到该地区的消息。
My question is: I know there is an EventBus, I could subscribe my people to the event Bus, but I dont want them to recieve every message posted, I want them to recieve the messages of the region.
现在在akka,我们必须创建一个具有一定数量路由的路由器,
示例:
right now in akka, we have to create a router with a certain number of routees, example :
Router router = new router(person1, person2)
这很糟糕,因为在开始时该地区没有人,我不知道将加入我所在地区的人。
this is bad because At the beggining there is no one in the region, i don't know the people who will join my region.
有没有办法制作一种动态路由器:
例如:
is there a way to make a kind of dynamic router : example :
Region region = new region()
region.router = new Router()
Person person1 = new Person()
region.router.subscribe(person1);
region.router.tell("hello",null);
推荐答案
您的解决方案已经非常接近:您需要路由器,但不是特制的预制件之一。相反,只需写一个向订阅者转发消息的演员:
Your solution is already very close: you need a router, but not one of the special-made pre-fabricated ones. Instead just write an actor which forwards messages to subscribers:
class MyRouter extends UntypedActor {
final Set<ActorRef> subscribers = new HashSet<ActorRef>();
@Override public void onReceive(Object msg) {
if (msg instanceof Subscribe) {
subscribers.add(getSender());
} else if (msg instanceof Unsubscribe) {
subscribers.remove(getSender());
} else {
for (ActorRef target: subscribers) {
target.tell(msg, getSender());
}
}
}
}
这篇关于Akka(java),非阻止广播给所有孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!