need help with sse streaming of new records, postgresql, rails4

26 views
Skip to first unread message

Эдуард Хафизов

unread,
Oct 28, 2015, 10:05:02 AM10/28/15
to Ruby on Rails: Talk
I need to make realtime updates for all subscribers. After creating new record i need to publish it for all subscribers. 
I found a solution using postgre listen/notify
In controller: 
def index
  response
.headers['Content-Type'] = 'text/event-stream'
  sse
= SSE.new(response.stream)
 
begin
   
Comment.on_change do |data|
      sse
.write(data)
   
end
 
rescue IOError
   
# Client Disconnected
  ensure
    sse
.close
 
end
  render nothing
: true
end

and model
[...]
after_create
:notify_comment_added
[...]
private

def notify_comment_added
 
Comment.connection.execute "NOTIFY comments, 'data'"
end


class << self
 
def on_change
   
Comment.connection.execute "LISTEN comments"
    loop
do
     
Comment.connection.raw_connection.wait_for_notify do |event, pid, comment|
       
yield comment
     
end
   
end
 
ensure
   
Comment.connection.execute "UNLISTEN comments"
 
end
end


Problems are
1) Every listeners occupies a connection to db, and after some clients its reach maximum and i got ActiveRecord timeout
2) it works only with config.cache_classes = true and config.eager_load = true  otherwise servers froze on 1-2nd execution of controller. And its a big pain to restart server after every small change.

Does rails have any another solutions to perform this task? 




Reply all
Reply to author
Forward
0 new messages