0

I would like to achieve following behavior, having two applications. Whenever user of one application makes an entry in the database, I would like to inform the client who is using different application, database is shared. I am using rails. To achieve this I have tried to use redis pub/sub, and server side events, it worked but every time client was moving from page to another one new connection to redis was spawned and the old wasn't released which caused server to crash. Is there any other suggestions how this issue can be solved.

class EventController < ApplicationController
include ActionController::Live

 def index
 ActiveRecord::Base.clear_active_connections!
 response.headers['Content-Type'] = 'text/event-stream'
 redis = Redis.new
 @last_active = Time.zone.now
 redis.subscribe('event', 'heartbeat') do |on|
    on.message do |pattern, event, data|
      if event == 'heartbeat'
        idle_time = (Time.zone.now - @last_active).to_i
        if idle_time > 2.minutes
          redis.unsubscribe
        end
      else
        @last_active = Time.zone.now
      end
      response.stream.write(data, event: 'new:verification')
    end
 end
 rescue IOError
 rescue ClientDisconnected
 ensure
 redis.quit
 response.stream.close
 end

end

I also have tried multiple implementation from this thread Redis + ActionController::Live threads not dying

Community
  • 1
  • 1
mr. Holiday
  • 1,780
  • 2
  • 19
  • 37
  • Please show us your code. – Aleksei Matiushkin Jul 22 '16 at 11:30
  • Do not do it from the controller. Use a rake task or something similar. Then, when you receive a message, create a notification by inserting a record for the target user either to the database, or in some shared cache. Check for this record from the controller and display the notification if present. – Mladen Jablanović Jul 22 '16 at 11:44
  • @MladenJablanović if I understood you correctly, I need to create a rake task which will subscribe to the redis channel instead of subscribing in the controller? – mr. Holiday Jul 22 '16 at 11:46
  • yes. take a look at http://stackoverflow.com/questions/22644761/redis-pub-sub-on-rails for example. Personally, I never did it so perhaps there's even better way, but your controller is definitely not a place for that. – Mladen Jablanović Jul 22 '16 at 11:50

0 Answers0