現在的位置: 首頁 > 資料庫 > 正文

Redis 的 Pub/Sub 怎樣以WebSockets為前端的類EventMachine實現

2020年07月02日 資料庫 ⁄ 共 1409字 ⁄ 字型大小 評論關閉

  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實現」的內容,希望對大家有用。更多資訊請關注學步園。學步園,您學習IT技術的優質平台!

抱歉!評論已關閉.