如何解决接收当前所有用户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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。