【问题标题】:Rails 5 - Action Cable - list of connected usersRails 5 - Action Cable - 已连接用户列表
【发布时间】:2016-04-16 10:27:34
【问题描述】:

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

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

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

【问题讨论】:

  • 你找到解决办法了吗?
  • @dedekm,你能分享你的解决方案吗?谢谢。

标签: real-time ruby-on-rails-5 actioncable


【解决方案1】:

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

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

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

【讨论】:

  • 你是怎么做到的? Rails 中的 Thread 全局变量存在一些问题,那么我们如何在实时服务器上保存非持久数据?
  • 嗨,@Matrix。如果您有多个 Web 实例,我建议您使用 Redis 之类的东西来持久化它。
【解决方案2】:

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/

或类似How To use devise_token_auth with ActionCable for authenticating user?

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-28
      • 2018-05-11
      • 1970-01-01
      • 2017-08-23
      • 2021-05-29
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      相关资源
      最近更新 更多