Created
February 21, 2016 22:21
-
-
Save mattweldon/24f3cc598d4ecaf2acd1 to your computer and use it in GitHub Desktop.
Simple PubSub implementation using Redix (Exredis)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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