[英]What is the best way to receive all current user ActionCable connections?
当用户关闭浏览器中的所有选项卡时,我需要监视用户连接并将用户标记为离线。
我想,我应该检查 .unsubscribe 方法中的用户连接数,并在连接数为零时将用户标记为离线。
但是如何接收当前用户的所有连接呢? 或者最好的方法是什么?
Rails 指南在这里有(一半)这个例子: https://guides.rubyonrails.org/action_cable_overview.html#example-1-user-appearances
基本上,您创建了一个 AppearanceChannel 并且每个用户都订阅了它。 订阅调用出现 function 为 current_user,然后可以广播出去。
我目前的解决方案:
我的频道.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.