更具体地ActionCable
(和 Redis)......
假设这个频道:
class RoomChannel < ApplicationCable::Channel
end
从 ActionCable 获取 Redis 适配器,而不是自己创建它(您需要提供 URL config/cable.yml
):
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] }