-
-
Save nanounanue/1145714 to your computer and use it in GitHub Desktop.
Redis PubSub client with ruby/cool.io (cool.io is a high performance event library for Ruby built on top of libev)
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 'rubygems' | |
require 'cool.io' | |
require "redis/connection/command_helper" | |
class RedisPubsub < Cool.io::TCPSocket | |
include ::Redis::Connection::CommandHelper | |
event_callback :on_subscribe, :on_unsubscribe, :on_message | |
attr_accessor :args | |
def subscribe(*channels) | |
@channels = channels | |
return unless @connected | |
send_subscribe | |
end | |
def send_subscribe | |
# puts "redis SUBSCRIBE " + @channels.join(", ") | |
write build_command(['SUBSCRIBE'] + @channels) | |
end | |
def on_connect | |
@connected = true | |
send_subscribe if @channels | |
end | |
def on_read(data) | |
val = [] | |
data.split.each_with_index { |o,i| val << o if i.even? } | |
return if val[1].to_s.length <= 0 || !respond_to?("on_#{val[1]}") | |
# puts "redis on_read #{val}" | |
if @args | |
send "on_#{val[1]}", val[2..-1], @args | |
else | |
send "on_#{val[1]}", val[2..-1] | |
end | |
end | |
end | |
################################################################## | |
# simple example | |
if $0 == __FILE__ | |
sub = RedisPubsub.connect('localhost', 6379) | |
sub.subscribe :first, :second | |
sub.on_message do |data| | |
channel, msg = data | |
puts "#{channel}: #{msg}" | |
end | |
sub.attach(Cool.io::Loop.default) | |
cool.io.run | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment