Skip to content

Instantly share code, notes, and snippets.

@mattweldon
Created February 21, 2016 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattweldon/24f3cc598d4ecaf2acd1 to your computer and use it in GitHub Desktop.
Save mattweldon/24f3cc598d4ecaf2acd1 to your computer and use it in GitHub Desktop.
Simple PubSub implementation using Redix (Exredis)
defmodule PubSub do
def broadcast(channel, topic, payload) do
{:ok, client} = Exredis.start_link
payload = payload |> Map.put(:topic, topic)
client |> Exredis.Api.publish channel, Poison.encode!(payload)
end
def subscribe(channel, module) do
sup = spawn_link fn -> accept_messages(module) end
{:ok, client_sub} = Exredis.Sub.start_link
pid = Kernel.self
client_sub |> Exredis.Sub.subscribe channel, fn(msg) ->
send pid, msg
end
receive do
msg ->
accept_messages(module)
end
{:ok, sup}
end
def accept_messages(module) do
receive do
{:message, channel, payload, pid} ->
payload = SyproPubSub.parse_payload(payload)
module.process_payload(payload["topic"], payload)
accept_messages(module)
msg ->
accept_messages(module)
end
end
def parse_payload(payload) do
Poison.Parser.parse!(payload)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment