What are the different ways of handling events in a publish-subscribe system?
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(); }
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 :
- You don't have to maintain message routing/dispatching by yourself
- Each listener will have a single responsibility
- In case of any scale up scenario you can add more listeners for any message type without touching unrelated listeners.
That is all I can think of.
I hope this helps.
精彩评论