[关闭]
@elibinary 2016-07-09T04:56:59.000000Z 字数 3537 阅读 1189

Rails即时通讯之 ActionCable

未分类


上一篇介绍了 MessageBus 的即时通讯的解决方案,主要是利用轮训长轮询等策略。本片就来介绍一下基于 websocket 的实时通信框架 ActionCable 。

ActionCable 适配了Redis的pub/sub机制,还有pgsql的notify机制,你可以通过设置来选择想要使用的适配器。ActionCable 的核心便是 ActionCable::Connection::Base 以及 ActionCable::Channel::Base, client可以通过websocket连接订阅 channel,channel会实时广播消息给订阅者。大致先介绍道这里,下面先看看如何来使用 ActionCable

使用

首先来创建一个 channel ,服务器通过channel发布消息,客户端通过对应的channel订阅消息

  1. # app/channels/message_channel.rb
  2. class MessagesChannel < ApplicationCable::Channel
  3. def subscribed
  4. stream_from "messages_channel_#{current_user.id}"
  5. end
  6. def unsubscribed
  7. end
  8. end

其中 subscribed 方法是当客户端连接上来的时候被调用,unsubscribed 是当客户端与服务器失去连接时被调用。
这样一个简单的 message channel 就可以投入使用了,接下来就是 client 订阅想要的 channel 了

  1. App.cable.subscriptions.create "MessagesChannel",
  2. connected: ->
  3. disconnected: ->
  4. received: (data) ->
  5. $('#messages').append data["title"], body: data["body"]

这样当 client connected 的时候就将成功订阅属于它的频道, 当服务器端广播消息给此 channel 时,client就会通过 received 事件接受并 append 收到的消息。下面还差一步就是服务器如何广播一条消息

  1. # Somewhere in your app this is called
  2. ActionCable.server.broadcast "messages_channel_#{current_user.id}", { title: 'test', body: 'test666' }
  3. # The ActionCable.server.broadcast call places a message in the Action Cable pubsub queue under a separate broadcasting name for each user
  4. # The data is the hash sent as the second parameter to the server-side broadcast call, JSON encoded for the trip across the wire, and unpacked for the data argument arriving to #received.

进阶

上面简单介绍了 ActionCable 的其中一种用法,更多的用法可以去看官网的例子以及多多开脑洞。下面来看看使用中的一些要注意的地方和小细节。

Action Cable is powered by a combination of websockets and threads. All of the connection management is handled internally by utilizing Ruby’s native thread support, which means you can use all your regular Rails models with no problems as long as you haven’t committed any thread-safety sins.

But this also means that Action Cable needs to run in its own server process. So you'll have one set of server processes for your normal web work, and another set of server processes for the Action Cable.

The Action Cable server does not need to be a multi-threaded application server. This is because Action Cable uses the Rack socket hijacking API to take over control of connections from the application server. Action Cable then manages connections internally, in a multithreaded manner, regardless of whether the application server is multi-threaded or not. So Action Cable works with all the popular application servers -- Unicorn, Puma and Passenger.

Action Cable does not work with WEBrick, because WEBrick does not support the Rack socket hijacking API.

文档这么说的,其实就是说建议最好把将 ActionCable 独立部署在单独的 server 进程上面以避免阻塞。另外虽然它是依赖于 Ruby’s native thread support 的,但是它将 thread 交给了 rock hijacking 去处理了,所以并不需要一定部署在多线程的 server 中。

ActionCable 的介绍就先到这里,之后在使用中遇到的问题以及细节会在做总结。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注