在发布-订阅系统中处理事件有哪些不同的方法?
在每个订阅者等待多种类型事件的发布-订阅系统中,是否有比简单交换机更好的处理解决方案?
假设我们有 2 个发布者,Pub1 和 Pub2; Pub1 发送两种类型的事件 Pub1-eventA 和 Pub1-eventB,Pub2 也是如此,分别发送 Pub2-eventA 和 Pub2-eventB
另一方面,我们有一个客户端 Sub1,它订阅 Pub1 和 Pub2 的事件;
您将如何在 Sub1 侦听器中处理这些事件?
这里有一些可能性:
一个侦听器,一个大开关(难以维护):
Listener{
HandleEvent(event){
if(event.type == Pub1-eventA)
Action1.execute();
if(event.type == Pub1-eventB)
Action2.execute();
if(event.type == Pub2-eventA)
Action3.execute();
if(event.type == Pub2-eventB)
Action4.execute();
}
}
一个侦听器和一个关联映射:
Map<event-type, Action> ActionMap
Listener{
Action = ActionMap[event-type]
Action.execute();
}
每种事件类型一个侦听器:
ListenerPub1-eventA{ check(event-type); Action1.execute(); }
ListenerPub1-eventB{ check(event-type); Action2.execute(); }
ListenerPub2-eventA{ check(event-type); Action3.execute(); }
ListenerPub2-eventB{ check(event-type); Action4.execute(); }
In a publish-subscribe system where each subscriber waits for several types of events, is there a better handling solution than a simple switch ?
let's say we have 2 publishers, Pub1 and Pub2; Pub1 sends 2 types of events Pub1-eventA and Pub1-eventB, the same for Pub2 with repectively Pub2-eventA and Pub2-eventB
On the other hand we have a client Sub1 which subscribes to Pub1 and Pub2's events;
How would you manage handling those events in a Sub1 listener?
Here some possibilities :
One listener, one big switch (hard to maintain):
Listener{
HandleEvent(event){
if(event.type == Pub1-eventA)
Action1.execute();
if(event.type == Pub1-eventB)
Action2.execute();
if(event.type == Pub2-eventA)
Action3.execute();
if(event.type == Pub2-eventB)
Action4.execute();
}
}
One listener and an association map :
Map<event-type, Action> ActionMap
Listener{
Action = ActionMap[event-type]
Action.execute();
}
One listener per event type :
ListenerPub1-eventA{ check(event-type); Action1.execute(); }
ListenerPub1-eventB{ check(event-type); Action2.execute(); }
ListenerPub2-eventA{ check(event-type); Action3.execute(); }
ListenerPub2-eventB{ check(event-type); Action4.execute(); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在“一个侦听器,一个大开关”和“一个侦听器和关联映射”中,每个事件仍将以单个隔离方法结束,但您必须在代码中维护事件的分派。
发布-订阅消息系统最重要的贡献是解耦发布者和订阅者。因此消息路由应该由中间件负责。如果您的中间件不具备消息路由功能,那么我建议每种事件类型使用一个侦听器,以便:
我能想到的就是这些。
我希望这有帮助。
In "One listener, one big switch" and in "One listener and an association map" each event will still end up in a single isolated method but you will have to maintain the dispatching of events within your code.
The most important contribution of publish-subscribe messaging systems is decoupling publishers and subscribers. So message routing should be the responsibility of your middleware. If your middleware is not capable of message routing, then I would suggest going for one listener per event type so that :
That is all I can think of.
I hope this helps.