Last active
April 27, 2016 01:47
-
-
Save rickychilcott/c38e905822f618e89ffd372b69f160a8 to your computer and use it in GitHub Desktop.
Simple example of using Tubesock with Redis psubscribe to handle redis messages
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
class MessagesController < ApplicationController | |
include Tubesock::Hijack | |
def index | |
hijack do |tubesock| | |
tubesock.onopen do | |
@open = true | |
end | |
tubesock.onmessage do |data| | |
@client_id = data.strip | |
puts "Set client_id to #{@client_id}" | |
tubesock.send_data({client_id: @client_id}.to_json) | |
end | |
# Listen on its own thread | |
redis_thread = Thread.new do | |
Redis.new.psubscribe('device/*') do |on| | |
on.pmessage do |pattern, event, data| | |
puts "Send data from redis" | |
tubesock.send_data({message: data}.to_json) if should_send?(event) | |
end | |
end | |
end | |
heartbeat_thread = Thread.new do | |
loop do | |
sleep 10 | |
puts "Send heartbeat!" | |
tubesock.send_data({last_heartbeat_at: Time.now.to_i}.to_json) if @open | |
end | |
end | |
tubesock.onclose do | |
@open = false | |
redis_thread.kill | |
heartbeat_thread.kill | |
end | |
end | |
end | |
private | |
def client_id_set? | |
@client_id.present? | |
end | |
def should_send?(event) | |
client_id_set? and event.include?("device/#{@client_id}") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment