我會建議使用的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
感謝Martin,那就是我在想什麼。我現在只需要將它全部保留在同一個過程中,並在稍後找出解決方案。 – fridgerator
我對當前的架構使用了類似的東西。除了我自己寫的外,我使用了一個nginx插件。看看https://github.com/wandenberg/nginx-push-stream-module它工作得很好。 –