[英]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.我想,我应该检查 .unsubscribe 方法中的用户连接数,并在连接数为零时将用户标记为离线。
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 Rails 指南在这里有(一半)这个例子: https://guides.rubyonrails.org/action_cable_overview.html#example-1-user-appearances
Basically, you create an AppearanceChannel and every user is subscribed to it.基本上,您创建了一个 AppearanceChannel 并且每个用户都订阅了它。 Subscribing calls the appear function for the current_user, which can then be broadcast out.
订阅调用出现 function 为 current_user,然后可以广播出去。
My current solution:我目前的解决方案:
my_channel.rb我的频道.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用户.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.