Implementing Pub/Sub Messaging
1. Publishing Messages
| Command | Returns |
PUBLISH channel message | Count of clients that received |
SPUBLISH channel message | Sharded variant for Cluster 7.0+ |
2. Subscribing to Channels
| Command | Description |
SUBSCRIBE ch1 ch2 ... | Enters subscribe state; limited commands allowed |
SSUBSCRIBE ch1 ... | Sharded subscribe for Cluster |
3. Unsubscribing from Channels
| Command | Behavior |
UNSUBSCRIBE [ch ...] | No args unsubscribes from all |
PUNSUBSCRIBE [pat ...] | Pattern unsubscribe |
4. Using Pattern Subscriptions
| Command | Description |
PSUBSCRIBE pat [pat ...] | Glob pattern (e.g. news.*) |
5. Using Sharded Pub/Sub
| Command | Notes |
SPUBLISH / SSUBSCRIBE | Channel hashed to slot; scales horizontally in Cluster 7.0+ |
6. Listing Active Channels
| Command | Returns |
PUBSUB CHANNELS [pattern] | Channels with ≥1 subscriber |
PUBSUB SHARDCHANNELS | Sharded equivalent |
7. Counting Subscribers
| Command | Returns |
PUBSUB NUMSUB [ch ...] | Per-channel subscriber count |
8. Counting Pattern Subscribers
| Command | Returns |
PUBSUB NUMPAT | Total active pattern subscriptions |
9. Understanding Message Delivery Guarantees
Warning: Pub/Sub is fire-and-forget. Offline subscribers miss messages. Use Streams for durable delivery.
| Guarantee | Detail |
| At-most-once | No persistence, no retries |
| Order | Per publisher, FIFO |
10. Handling Connection Issues
| Risk | Mitigation |
| Slow consumers | Tune client-output-buffer-limit pubsub |
| Disconnect | Re-subscribe on reconnect; backfill via Stream |
11. Implementing Fan-Out Pattern
Example: Broadcast event to all listeners
// Publisher
jedis.publish("events.user.signup", json);
// Subscriber
jedis.subscribe(new JedisPubSub() {
public void onMessage(String ch, String msg) { handle(msg); }
}, "events.user.signup");