问题描述
我需要监视用户连接,并在用户关闭浏览器中的所有选项卡时将用户标记为脱机。
我想,我应该使用.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