【问题标题】:What is the best way to receive all current user ActionCable connections?接收所有当前用户 ActionCable 连接的最佳方式是什么?
【发布时间】:2020-08-12 07:16:34
【问题描述】:

当用户关闭浏览器中的所有选项卡时,我需要监控用户连接并将用户标记为离线。

我想,我应该检查 .unsubscribe 方法中的用户连接数,并在连接数为零时将用户标记为离线。

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

【问题讨论】:

    标签: ruby-on-rails actioncable


    【解决方案1】:

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

    基本上,您创建一个 AppearanceChannel 并且每个用户都订阅了它。订阅调用current_user的appear函数,然后可以广播出去。

    【讨论】:

    • 但是如果用户打开几个标签,然后关闭其中一个呢? AppearanceChannel.unsubscribed 将被解雇,用户将消失。这不是很有用的例子(只有当他关闭所有浏览器中的所有标签时,我才需要将用户标记为离线
    【解决方案2】:

    我目前的解决方案:

    我的频道.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
    

    用户.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-23
      • 2010-09-10
      • 2017-07-31
      • 2016-05-06
      • 2017-11-30
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      相关资源
      最近更新 更多