20

我见过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 - 如何显示已连接用户数?

4

2 回答 2

17

如果使用redis,您可以看到所有的 pubsub 频道。

[2] pry(main)> Redis.new.pubsub("channels", "action_cable/*")
[
    [0] "action_cable/Z2lkOi8vbWFvY290LXByb2plL3QvUmVzcG9uXGVyLzEx",
    [1] "action_cable/Z2lkOi8vbWFvY290LXByb2plL3QvUmVzcG9uXGVyLzI"
]

这将显示所有 Puma 工作人员的所有 websocket 连接。如果您有多个服务器,它可能也会在此处显示这些服务器。

于 2016-03-26T01:00:57.583 回答
15

更具体地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] }
于 2017-11-08T13:19:53.900 回答