如何找出与ActionCable连接的人?
我见过ActionCable.server.open_connections_statistics
, ActionCable.server.connections.length
, ActionCable.server.connections.map(&:statistics)
, ActionCable.server.connections.select(&:beat).count
等等,不过这个只是“每个进程”(服务器,控制台,服务器工作者等)。 我如何找到目前订阅ActionCable的所有人 ? 这应该在每个环境(开发,登台,生产)中的任何Rails进程上返回相同的值。 例如,在开发控制台中,您还可以看到开发服务器上的连接,因为理论上它们使用相同的订阅适配器(redis,async,postgres)。
Rails 5.0.0.beta3,Ruby 2.3.0
相关的ActionCable – 如何显示已连接用户的数量?
如果使用redis
您可以看到所有pubsub频道。
[2] pry(main)> Redis.new.pubsub("channels", "action_cable/*") [ [0] "action_cable/Z2lkOi8vbWFvY290LXByb2plL3QvUmVzcG9uXGVyLzEx", [1] "action_cable/Z2lkOi8vbWFvY290LXByb2plL3QvUmVzcG9uXGVyLzI" ]
这将显示所有Puma工作人员的所有websocket连接。 如果你有多台服务器,它也可能在这里显示。
更具体的ActionCable
(和Redis)……
假设这个频道:
class RoomChannel < ApplicationCable::Channel end
从ActionCable获取Redis适配器而不是自己创建(否则需要从config/cable.yml
提供URL):
pubsub = ActionCable.server.pubsub
获取频道的名称,包括您在config/cable.yml
指定的channel_prefix:
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://// 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] }