Redis is famous enterprise key/value data store which provides simple messaging using publisher/subscriber. I’ve decided to use the system to notify remote nodes (components) about a change of state between those components.
Spring among the others allows to use it’s templating system to decouple business logic from messaging system used under the hood. The use of spring data for Redis guarantees a solution which does not utilize any redis command in the code.
Redis contains serialized content, either byte or string. So the last thing to reveal is domain model serialization. I’ve decided to fast binary serialization using Kryo framework as a winner of battle of serializators.
First of all, it’s necessary to define all dependant components. Obviously, usual component like spring itself missing.
I used domain model’s entity which hold identifier of our internal service, this is just UUID. The point is to setup kryo serializator which get the entity and returns byte. The entity itself is not important.
Redis Message Handler
The beautiful part is the complete definition of async message handling within xml configuration of redis message container.
Note that I used Jedis client as java redis client.
What is going on?
Message container references both redis factory and given list of message listeners. It’s a class (or set of classes) having registered method as a callback when a new message arrives.
The last property is channel with important channel name. The code uses two variables, first is redis host and already mentioned channel name.
The last thing to do is to define message listener containing callback method, MyEntityListener. The class instance is called always once new message arrive using channel topic.
Crucial point was to discover the signature of callback’s method because spring’s documentation is little bit sloopy. Quick look into org.springframework.data.redis.listener.adapter.MessageListenerAdapter’s onMessage shows the correct way.
Incoming message is automatically deserialized so the method accepts entity itself.
Look at previous code. Every redis related code is defined in spring’s context and container class. No boilerplate code. Pretty nice.
Architectural note should explicitly show that the entity serves as a notification only. This is very important as such messaging is not reliable. Although the entity holds some information all the persistent data is defined within another place, e.g. as key/value pairs. Approaching message just notifies subscriber that new content is available to refresh and it’s supposed to GET key(s).