2015-05-23 41 views
2

我使用websocket-rack構建聊天應用程序API。將websocket連接存儲到redis

我想在redis中存儲websocket連接(最終成爲Rack::WebSocket::Handler::Base::Connection的一個實例),以便它們可以被過濾並從其他進程引用。

我意識到我可以store the connections in an class variable,但這不起作用。

顯然,對象本身不能存儲在redis中,但是我可以存儲websocket_key和其他一些信息,並在我想發送消息時重建連接對象?

回答

1

莫名其妙地重建連接對象,當我想發送消息給它?

你不能重建它,你需要保持它活着,否則斷開你的客戶端。

維護WebSocket連接(活動)的過程還需要提供一個API,以便其他進程可以告訴它代表它們發送消息。

例如,這可能是一個簡單的私人(只接受來自localhost連接),你與兩個參數發送POST信息HTTP API:

  1. 要發送
  2. 要誰的消息將消息發送到
+0

感謝Martin,那就是我在想什麼。我現在只需要將它全部保留在同一個過程中,並在稍後找出解決方案。 – fridgerator

+0

我對當前的架構使用了類似的東西。除了我自己寫的外,我使用了一個nginx插件。看看https://github.com/wandenberg/nginx-push-stream-module它工作得很好。 –

1

我會建議使用的WebSockets框架,如the Plezi web-app framework,這將同時處理WebSocket連接IO,並幫助您廣播通過在多個流程的數據* Redis服務器。

(*注意:儘管Redis的可存儲數據,它不能存儲對象,絕對不能儲存活插座)

例如:Plezi會讓你叉你的服務器,它會自動使用Redis的廣播在不同進程中的WebSockets之間,或者在不同的機器/單播數據:

require 'plezi' 
ENV['PL_REDIS_URL'] = "redis://username:[email protected]:6379" 
# fork to 4 processes, each will have at least 2 Redis connections 
GR::Settings.set_forking 4 
# ... plezi code 
Plezi.start # now it will fork. 

使用the Plezi framework看起來會像這樣的工作聊天服務器*:

*這只是在irb終端中運行的草案。通過plezi new app_name命令設置的Plezi應用程序看起來會更有條理。

require 'plezi' 

# # optional Redis URL: automatic broadcasting across processes: 
# ENV['PL_REDIS_URL'] = "redis://username:[email protected]:6379" 

class ChatController 
    def index 
     %q{  This is a Plezi chat demo app using websockets. 
     To test this app, go to: http://www.websocket.org/echo.html 
     In the Location URL fill in the following url: ws://localhost:3000/nickname 
     Click Connect. No the app will act as a chat demo server with your browser as the client. 

     Try running the demo from two different browser windows to see chat messages between windows. 
     remember to set the correct Location URL in each window.} 
    end 
    def on_message data 
     msg = "#{params[:id] ? params[:id].to_s : 'unknown'}: #{data}" 
     broadcast :_send, msg 
     _send msg 
     true 
    end 
    def _send message 
     response << message 
    end 
end 

# starts listening with default settings, on port 3000 
listen 

# this is automatically converted to the RESTful route: '/(:id)' 
route '/', ChatController 

# exit terminal to start server 
exit