Skip to content

Publish / Subscribe

The included RedisPubSubService uses Redis' SUBSCRIBE/PUBLISH commands to provide a messaging service, which allows threads to communicate across JVM instances.

It multiplexes many (thousands of) threads/clients onto the same underlying channel on Redis. This is more scalable than letting each thread/client start its own dedicated subscription-connection to Redis.

It can for example be used to distribute events among JVMs/nodes and route those to their respective WebSocket sessions.

Things to be aware of:

  • Delivery is at-most-once: messages published while a node is disconnected are lost.
  • Each message is handled on a new virtual thread.
  • A subscriber also receives the messages it publishes itself.

Set up a shared RedisPubSubService

// share this as a bean/singleton. It handles re-connect upon failures internally.
val redisPubSubService = RedisPubSubService(
    connectionPool = connectionPool,
).apply { start() }

// on shutdown
redisPubSubService.stop()

Start listening for messages/events

Start listening on the channel "foo":

val subscription = redisPubSubService.subscribe("foo") { msg: ByteArray ->
    println(msg.toString(redisStringCharset))
}

Send messages

Send a message to the channel "foo":

subscription.publish("test".toByteArray(redisStringCharset))

Stop listening

subscription.close()