Search code examples
javadesign-patternsjmsactivemq-classic

Handling a big amount of JMS message types


i'm new to jms, and i'm currently designing a BattleShip game. I'm using jms with activemq for the communication between them, so far i made 4 classes for jms communication which are Topic and Queue receivers and senders with simple methods of changing destination and sending.

Now i'm facing a problem when want to handle these messages, I've decided every message will be delivered via ObjectMessage and the inner object will tell the listener how to handle it.

I have 5 different categories for messages : Authentication, Data (Such as highscores, replays etc), InGameMessages (ShipRegistration, TurnUpdate and so on), ChatMessage, MatchMakingMessages (Only GameSearch and GameSearchCancel),

So i thought it will be a good idea to add a MessageType enum to each message, but eventually I ended up writing the listener with over than 20 cases at the switch statement and with a huge amount of class castings.

Now I want to write it all over again, but i'm still stuck on the message handling since I can't find a different idea, or any design pattern which can handle this issue.

Any thoughts?


Solution

  • You can set a JMS property with the value of your "MessageType" enum. JMSType is a built-in property that you can use for that or you can add your own property to every message (with a name like "MessageType")

    On the client side, read the message and test the value of that property and convert it back to the enum in a switch statement then perform the casting of the message based on the object of the class associated with the message, Use only one topic, each client subscribing to the topic.

    Instead of the switch statement, you can have one listener per message type based on a JMS selector, each one selecting only one value of the JMS property (ie MessageType). All depends of your use case of course (strict ordering etc.)