Actioncable 连接的用户列表 [英] Actioncable connected users list
本文介绍了Actioncable 连接的用户列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我像这样在 ActionCable 中对用户进行身份验证:
I'm authenticating users in ActionCable like this:
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
logger.add_tags 'ActionCable', current_user.name
end
protected
def find_verified_user
if verified_user = User.find_by(id: cookies.signed[:user_id])
verified_user
else
reject_unauthorized_connection
end
end
end
end
是否可以获取已连接的用户列表?我用谷歌搜索但只发现了这个 stackoverflow 问题:首先,第二
Is it possible to get connected users list ? I googled but found only this stackoverflow questions: first, second
推荐答案
你有点不得不推出自己的用户跟踪.
Ya kinda have to roll your own user-tracking.
重要的部分如下:
# connection
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :uid
def connect
self.uid = get_connecting_uid
logger.add_tags 'ActionCable', uid
end
protected
# the connection URL to this actioncable/channel must be
# domain.tld?uid=the_uid
def get_connecting_uid
# this is just how I get the user id, you can keep using cookies,
# but because this key gets used for redis, I'd
# identify_by the user_id instead of the current_user object
request.params[:uid]
end
end
end
# Your Channel
def subscribed
stop_all_streams
stream_from broadcasting_name
ConnectedList.add(uid)
end
def unsubscribed
ConnectedList.remove(uid)
end
然后在模型中:
class ConnectedList
REDIS_KEY = 'connected_nodes'
def self.redis
@redis ||= ::Redis.new(url: ActionCableConfig[:url])
end
# I think this is the method you want.
def self.all
redis.smembers(REDIS_KEY)
end
def self.clear_all
redis.del(REDIS_KEY)
end
def self.add(uid)
redis.sadd(REDIS_KEY, uid)
end
def self.include?(uid)
redis.sismember(REDIS_KEY, uid)
end
def self.remove(uid)
redis.srem(REDIS_KEY, uid)
end
end
来自:https://github.com/NullVoxPopuli/mesh-relay/
这篇关于Actioncable 连接的用户列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文