Rails 5 - Action Cable - 连接用户列表

7
我正在学习Rails 5和Action Cable,想要展示所有已连接注册用户的名称列表(类似Facebook的绿色圆圈)。我已经成功获取了用户的名称,但现在正在考虑最佳存储方式。在Node中,我会简单地在服务器上使用一个数组,但我知道在ActionCable中这是不可能的。那么,最有效的方法是什么?将它们存储在数据库中(Postgres、Redis)?

1
你找到任何解决方案了吗? - user525717
@dedekm,你能分享一下你的解决方案吗?谢谢。 - opensource-developer
3个回答

2

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

如果不需要,请随时在Rails服务器上使用内存数组。也许是memcache或类似的东西。

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


你怎么做这个?在Rails中有一些关于Thread全局变量的问题,那么我们如何在实时服务器上保存非持久化数据呢? - Matrix
嗨,@Matrix。如果你有多个Web实例,我建议你使用类似Redis的东西来持久化它。 - ekampp

1
我认为最好的方法是将它们存储在Redis中,因为它非常快。然而,更重要的是,如果您使用Postgres或任何其他RDBMS,您将在数据库上创建不必要的负载。

1
Users中添加一个online字段。
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}”消息并在用户头像上设置绿点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接