- Install the
redisgem - Start
subscribe.rbwithruby subscribe.rb, this will not exit - Run
ruby publish.rband you should see the message being received in the output ofsubscribe.rb
Created
May 16, 2014 08:38
-
-
Save joshnesbitt/f0fde584857b97798b63 to your computer and use it in GitHub Desktop.
Simple Redis pub/sub
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
| 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 |
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
| require_relative 'notifications' | |
| Notifications.publish('user.sign_in', { user_id: 1 }) |
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
| 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