Redis.PubSub (Redis v0.7.1)

Copy Markdown View Source

Pub/Sub client for Redis.

Manages a dedicated pub/sub connection and routes messages to subscribing Elixir processes as regular Erlang messages.

Usage

{:ok, ps} = Redis.PubSub.start_link(port: 6379)
:ok = Redis.PubSub.subscribe(ps, "mychannel", self())

receive do
  {:redis_pubsub, :message, channel, payload} ->
    IO.puts(channel <> ": " <> payload)
end

:ok = Redis.PubSub.unsubscribe(ps, "mychannel", self())

Message Format

{:redis_pubsub, :message, channel, payload}
{:redis_pubsub, :pmessage, pattern, channel, payload}
{:redis_pubsub, :subscribed, channel_or_pattern, count}
{:redis_pubsub, :unsubscribed, channel_or_pattern, count}

Options

  • :host - Redis host (default: "127.0.0.1")
  • :port - Redis port (default: 6379)
  • :password - authentication password
  • :username - authentication username
  • :name - GenServer name registration
  • :timeout - connection timeout ms (default: 5_000)

Summary

Functions

Returns a specification to start this module under a supervisor.

Subscribe subscriber to a pattern. Messages arrive as {:redis_pubsub, :pmessage, pattern, channel, payload}.

Unsubscribe subscriber from a pattern.

Stops the pub/sub connection.

Subscribe subscriber to channel. Messages arrive as {:redis_pubsub, :message, channel, payload}.

Returns current subscription state: channels and patterns with their subscriber counts.

Unsubscribe subscriber from channel.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

psubscribe(pubsub, patterns, subscriber \\ self())

@spec psubscribe(GenServer.server(), String.t() | [String.t()], pid()) ::
  :ok | {:error, term()}

Subscribe subscriber to a pattern. Messages arrive as {:redis_pubsub, :pmessage, pattern, channel, payload}.

punsubscribe(pubsub, patterns, subscriber \\ self())

@spec punsubscribe(GenServer.server(), String.t() | [String.t()], pid()) ::
  :ok | {:error, term()}

Unsubscribe subscriber from a pattern.

start_link(opts \\ [])

@spec start_link(keyword()) :: GenServer.on_start()

stop(pubsub)

@spec stop(GenServer.server()) :: :ok

Stops the pub/sub connection.

subscribe(pubsub, channels, subscriber \\ self())

@spec subscribe(GenServer.server(), String.t() | [String.t()], pid()) ::
  :ok | {:error, term()}

Subscribe subscriber to channel. Messages arrive as {:redis_pubsub, :message, channel, payload}.

subscriptions(pubsub)

@spec subscriptions(GenServer.server()) :: map()

Returns current subscription state: channels and patterns with their subscriber counts.

unsubscribe(pubsub, channels, subscriber \\ self())

@spec unsubscribe(GenServer.server(), String.t() | [String.t()], pid()) ::
  :ok | {:error, term()}

Unsubscribe subscriber from channel.