We are only using jedis in order to keep the example simple.
Redis Commands used
subscribe
this is used in order to subscribe to one or more channels:
unsubscribe
unsubscribe current client to one or more channels:
psubscribe
instead of subscribing to a channel, this allows you to subscribe to one of more patterns:
for example if you subscribe to foo* it means that you will get the messages meant for all the channels that start with foo.
punsubscribe
unsubscribe from one or more patterns:
publish
publish sends a message to connected clients, returns the number of clients that got the message.
ping
sends a ping from a client to the server, optionally you can send a message and the ping will echo it.
or
Code walkthrough
We need to extend JedisPubSub in order to give our client functionality.
To keep this example simple we are only going to add very basic functionality, in order to know which client is the one that got the message we are adding a name field.
For subscribe, unsubscribe, psubscribe, punsubscribe and pong (which is the one that a successful ping triggers) we only print the information:
When receiving a message in the client apart from printing the information if the message is a ping then we will do a ping.
If receiving the String “exit” we will unsubscribe from that channel or pattern (in the case of client subscribed using psubscribe).
Then we only need to make a JedisPooled connection and used it to subscribe to a channel or pattern:
We need to run the subscribe and psubscribe on a thread since those are blocking operations.
In this example we are creating three clients, which we will identify as “onlyOne”, “oneAndTwo” and “pattern”, this doesn’t mean anything to redis, but it will be easier for us to keep track of whats happening.
“onlyOne” is subscribed to channel “dev.one”.
“oneAndTwo” is subscribed to channels “dev.one” and “dev.two”.
“pattern” is subscribed to the pattern “dev.*”.
With this we could send messages using publish on our RedisInsight CLI which should be running on http://localhost:8001/redis-stack/browser if we installed the redis-stack.
But we will also send messages using jedis.
For building the code run mvn package and a far jar will be generated on target and then you can run it like so java -jar RedisPubSub-1.0.jar.