這篇文章給大家介紹Redis 的 Pub/Sub如何以WebSockets為前端的類EventMachine實現,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
EventMachine是一個Ruby的事件驅動網絡庫,一個以Redis的Pub/Sub機制為后端,以WebSockets為前端的類EventMachine實現。下面億速云小編來講解下Redis的Pub/Sub怎樣以WebSockets為前端的類EventMachine實現?
Redis的Pub/Sub怎樣以WebSockets為前端的類EventMachine實現
前端代碼,創建Socket連接到本地8081端口,當有消息push過來的時候,將消息打印到指定的div里:
Redis的Pub/Sub怎樣以WebSockets為前端的類EventMachine實現
后端代碼:
require'redis'
require'em-websocket'
SOCKETS=[]
@redis=Redis.new(:host=>'127.0.0.1',:post=>6379)
#CreatingathreadfortheEMeventloop
Thread.newdo
EventMachine.rundo
#Createsawebsocketlistener
EventMachine::WebSocket.start(:host=>'0.0.0.0',:port=>8081)do|ws|
ws.onopendo
#WhensomeoneconnectsIwanttoaddthatsockettotheSOCKETSarraythat
#Iinstantiatedabove
puts'creatingsocket'
SOCKETS< end ws.onclosedo #UponthecloseoftheconnectionIremoveitfrommylistofrunningsockets puts'closingsocket' SOCKETS.deletews end end end end #Creatingathreadfortheredissubscribeblock Thread.newdo @redis.subscribe('ws')do|on| #Whenamessageispublishedto'ws' on.messagedo|chan,msg| puts"sendingmessage:#{msg}" #Sendoutthemessageoneachopensocket SOCKETS.each{|s|s.sendmsg} end end end sleep 開啟8081端口接受連接,同時連到Redis上訂閱ws這個key的消息 當前后端都啟動并連接上后,你就可以用如下代碼往Redis的ws這個key上寫消息,頁面上就能看到push過來的消息了: require'redis' @redis=Redis.new(:host=>'127.0.0.1',:post=>6379)
@redis.publish'ws','Somethingwitty'
關于Redis 的 Pub/Sub如何以WebSockets為前端的類EventMachine實現就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。