更具体的ActionCable(和 Redis)...
假设这个频道:
class RoomChannel < ApplicationCable::Channel
end
从 ActionCable 获取 Redis 适配器,而不是自己创建
(否则您需要提供来自 config/cable.yml 的 URL):
pubsub = ActionCable.server.pubsub
获取频道名称,包括您可能指定的频道前缀
在config/cable.yml:
channel_with_prefix = pubsub.send(:channel_with_prefix, RoomChannel.channel_name)
从RoomChannel获取所有连接的频道:
# pubsub.send(:redis_connection) actually returns the Redis instance ActionCable uses
channels = pubsub.send(:redis_connection).
pubsub('channels', "#{channel_with_prefix}:*")
解码订阅名称:
subscriptions = channels.map do |channel|
Base64.decode64(channel.match(/^#{Regexp.escape(channel_with_prefix)}:(.*)$/)[1])
end
如果您订阅了ActiveRecord 对象,假设为Room(使用stream_for),
您可以提取 ID:
# the GID URI looks like that: gid://<app-name>/<ActiveRecordName>/<id>
gid_uri_pattern = /^gid:\/\/.*\/#{Regexp.escape(Room.name)}\/(\d+)$/
chat_ids = subscriptions.map do |subscription|
subscription.match(gid_uri_pattern)
# compacting because 'subscriptions' include all subscriptions made from RoomChannel,
# not just subscriptions to Room records
end.compact.map { |match| match[1] }