7

我从 Rails 5 和 Action Cable 开始,我想显示所有已连接注册用户的名称列表(类似于 facebook 的绿色圆圈)。

我设法得到了用户的名字,但现在我在想什么是存储它们的最佳方式。在节点中,我只是在服务器上的一个数组中,但据我所知,这在 ActionCable 中是不可能的。

最有效的方法是什么?将它们存储在数据库中(postgres、redis)?

4

3 回答 3

2

有效性完全取决于您的需求。您需要数据库的持久性吗?

否则,您也可以随意在 Rails 服务器上使用内存中的数组。也许是 memcache,或者类似的东西。

这是一个非常开放的答案,因为这是一个非常开放的问题。我认为您应该考虑一下您的需求:)

于 2016-10-23T22:48:35.380 回答
1

我相信最好的方法是将它们存储在 redis 中,因为它真的很快。然而,更重要的是,如果您使用 postgres 或任何其他 RDBMS,您将在您的数据库上创建不必要的负载

于 2017-11-10T10:06:47.063 回答
1

online字段添加到Users

class AddOnlineToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :online, :boolean, default: false
  end
end

做一个出场频道

class AppearanceChannel < ApplicationCable::Channel
  def subscribed

    stream_from "appearance_channel"

    if current_user

      ActionCable.server.broadcast "appearance_channel", { user: current_user.id, online: :on }

      current_user.online = true

      current_user.save!

    end


  end

  def unsubscribed

    if current_user

      # Any cleanup needed when channel is unsubscribed
      ActionCable.server.broadcast "appearance_channel", { user: current_user.id, online: :off }

      current_user.online = false

      current_user.save!      

    end


  end 

end

AppearanceChannel确保所有访问者在进入您的站点时都订阅了(通过一些 JavaScript 调用,请参阅http://guides.rubyonrails.org/action_cable_overview.html#client-side-components)。将授权添加到 Action Cable:

像这样https://rubytutorial.io/actioncable-devise-authentication/

或类似的如何使用 devise_token_auth 和 ActionCable 来验证用户?

再次应用一些 JavaScript 代码来检测传入的“{ user: current_user.id, online: :on }”消息并在用户头像上设置绿点。

于 2017-04-20T14:40:32.650 回答