接收当前所有用户ActionCable连接的最佳方法是什么?

问题描述

我需要监视用户连接,并在用户关闭浏览器中的所有选项卡时将用户标记为脱机。

我想,我应该使用.unsubscribe方法检查用户连接数,并在连接数为零时将用户标记为脱机。

但是如何接收当前用户的所有连接? 要么 最好的方法是什么?

解决方法

Rails指南在此处有一个(一半)示例:https://guides.rubyonrails.org/action_cable_overview.html#example-1-user-appearances

基本上,您创建一个AppearanceChannel,每个用户都被订阅。订阅会调用current_user的外观函数,然后可以将其广播出去。

,

我当前的解决方案:

my_channel.rb

class MyChannel < ApplicationCable::Channel
  def subscribed
    make_user_online
  end

  def unsubscribed
    make_user_offline
  end

  private

  def make_user_online
    current_user.increment_connections_count
    current_user.online!
  end

  def make_user_offline
    return unless current_user.decrement_connections_count.zero?

    current_user.offline!
  end
end

user.rb

class User < ApplicationRecord
  def connections_count
    Redis.current.get(connections_count_key).to_i
  end

  def increment_connections_count
    val = Redis.current.incr(connections_count_key)
    Redis.current.expire(connections_count_key,60 * 60 * 24)
    val
  end

  def decrement_connections_count
    return 0 if connections_count < 1

    Redis.current.decr(connections_count_key)
  end

  private

  def connections_count_key
    "user:#{id}:connections_count"
  end
end

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...