Skip to content

Instantly share code, notes, and snippets.

@joshnesbitt
Created May 16, 2014 08:38
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 joshnesbitt/f0fde584857b97798b63 to your computer and use it in GitHub Desktop.
Save joshnesbitt/f0fde584857b97798b63 to your computer and use it in GitHub Desktop.
Simple Redis pub/sub

Usage

  • Install the redis gem
  • Start subscribe.rb with ruby subscribe.rb, this will not exit
  • Run ruby publish.rb and you should see the message being received in the output of subscribe.rb
require 'redis'
require 'json'
class Notifications
class << self
def redis
@redis ||= Redis.new
end
def subscribe(channel, &block)
redis.subscribe(channel.to_s) do |on|
on.subscribe do |name, active|
# NOOP
end
on.message do |name, payload|
block.call(decode_payload(payload))
end
on.unsubscribe do |name, active|
# NOOP
end
end
end
def publish(channel, payload = {})
redis.publish(channel, encode_payload(payload))
end
private
def encode_payload(payload)
JSON.generate(payload)
end
def decode_payload(payload)
JSON.parse(payload)
end
end
end
require_relative 'notifications'
Notifications.publish('user.sign_in', { user_id: 1 })
require_relative 'notifications'
trap(:INT) do
exit
end
Notifications.subscribe('user.sign_in') do |payload|
puts "Received payload from user.sign_in => #{payload.inspect}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment