我有一个没有Actor概念或任何内容的消息队列,因此在应用程序启动时,我想启动消息队列使用者,然后继续从队列中获取消息。现在,Play框架为每个Web套接字连接创建一个Actor,我希望能够将所有为特定ws端点保持Web Socket连接的Actor分组,以便我可以广播从特定消息队列中收到的所有消息。那些演员组的主题。
例如,每次客户端向以下任意一个端点发起请求时,以下端点都会创建一个Actor。因此,我们将其称为Foo演员和Bar演员。
ws://localshost/foo
ws://localshost/bar
https://www.playframework.com/documentation/2.5.x/JavaWebSockets
现在我要做的就是这个
伪代码:
messages = ReceiveMessagesFromQueue; // This is a live stream and it never stops.
for message in messages:
if message has key1:
List<FooActors> foo_list = getAllFooActors
broadcast(message, foo_list)
else if message has key2:
List<BarActors> bar_list = getAllBarActors
broadcast(message, bar_list)
我正在使用使用Java的最新版本的Play框架。
最佳答案
我会避免保留参与者列表的负担,而是使用Akka的Event Bus寻求更分离的方法。
这样做,您可以在逻辑上将每个主题的wensocket参与者(foo和bar)分组。这是松散耦合的,因为您的Websocket参与者或消息队列使用者都不需要了解另一端。他们只需要订阅或发布特定主题即可。
下面的代码基于lookup classification下显示的示例。
启动时,您的websocket参与者只需要订阅适当的主题,大致即可:
LookupBusImpl lookupBus = new LookupBusImpl();
lookupBus.subscribe(getSelf(), "foo"); // or "bar"
您的队列使用者只需在伪代码的基础上将消息发布到适当的主题即可:
LookupBusImpl lookupBus = new LookupBusImpl();
messages = ReceiveMessagesFromQueue;
for message in messages:
if message has key1:
lookupBus.publish(new MsgEnvelope("foo", System.currentTimeMillis()))
else if message has key2:
lookupBus.publish(new MsgEnvelope("bar", System.currentTimeMillis()))
对于分布式版本,请使用Distributed Publish Subscribe in Cluster。