简体   繁体   中英

What is the best way to receive all current user ActionCable connections?

I need to monitor user connections and mark user as offline when user closes all tabs in browser.

I suppose, I should check count of user connections in.unsubscribe method and mark user as offline when count of connections will be zero.

But how to receive all connections of current user? or What is the best way to do that?

The Rails guide has (half of) an example of this here: https://guides.rubyonrails.org/action_cable_overview.html#example-1-user-appearances

Basically, you create an AppearanceChannel and every user is subscribed to it. Subscribing calls the appear function for the current_user, which can then be broadcast out.

My current solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM