Redis.Commands.PubSub (Redis v0.8.0)

Copy Markdown View Source

Command builders for Redis Pub/Sub introspection and publishing.

This module provides pure functions that return Redis command lists for publishing messages and inspecting Pub/Sub state. These commands can be issued over a regular connection (unlike SUBSCRIBE/PSUBSCRIBE which require a dedicated Pub/Sub connection).

All functions return a command list (e.g. ["PUBLISH", "chan", "msg"]) and are intended for use with Redis.command/2 or Redis.pipeline/2.

Examples

# Publish a message to a channel
Redis.command(conn, PubSub.publish("events", "user_signed_up"))

# List active channels matching a pattern
Redis.command(conn, PubSub.pubsub_channels(pattern: "events:*"))

# Get subscriber counts for specific channels
Redis.command(conn, PubSub.pubsub_numsub(["events:login", "events:logout"]))

# Publish to a shard channel (Redis 7+)
Redis.command(conn, PubSub.spublish("orders:{us-east}", "new_order"))

Summary

Functions

PUBLISH -- post a message to a channel.

PUBSUB CHANNELS -- list active channels, optionally filtered by a glob pattern.

PUBSUB NUMSUB -- get the subscriber count for the given channels.

SPUBLISH -- post a message to a shard channel (Redis 7+).

Functions

publish(channel, message)

@spec publish(String.t(), String.t()) :: [String.t()]

PUBLISH -- post a message to a channel.

Returns the number of clients that received the message.

PubSub.publish("notifications", "hello")
#=> ["PUBLISH", "notifications", "hello"]

pubsub_channels(opts \\ [])

@spec pubsub_channels(keyword()) :: [String.t()]

PUBSUB CHANNELS -- list active channels, optionally filtered by a glob pattern.

PubSub.pubsub_channels()                        #=> ["PUBSUB", "CHANNELS"]
PubSub.pubsub_channels(pattern: "events:*")     #=> ["PUBSUB", "CHANNELS", "events:*"]

pubsub_numpat()

@spec pubsub_numpat() :: [String.t()]

pubsub_numsub(channels \\ [])

@spec pubsub_numsub([String.t()]) :: [String.t()]

PUBSUB NUMSUB -- get the subscriber count for the given channels.

Returns a flat list of channel/count pairs.

PubSub.pubsub_numsub(["ch1", "ch2"])
#=> ["PUBSUB", "NUMSUB", "ch1", "ch2"]

pubsub_shardchannels(opts \\ [])

@spec pubsub_shardchannels(keyword()) :: [String.t()]

pubsub_shardnumsub(channels \\ [])

@spec pubsub_shardnumsub([String.t()]) :: [String.t()]

spublish(shardchannel, message)

@spec spublish(String.t(), String.t()) :: [String.t()]

SPUBLISH -- post a message to a shard channel (Redis 7+).

Similar to publish/2 but targets shard channels, which are routed only to the cluster node owning the shard.

PubSub.spublish("orders:{us-east}", "new_order")
#=> ["SPUBLISH", "orders:{us-east}", "new_order"]