How do I find out who is connected to ActionCable?

前端 未结 2 1994
囚心锁ツ
囚心锁ツ 2020-12-10 02:41

I have seen ActionCable.server.open_connections_statistics, ActionCable.server.connections.length, ActionCable.server.connections.map(&:s

相关标签:
2条回答
  • 2020-12-10 03:18

    To be more specific for ActionCable (and to Redis)...

    Assuming this channel:

    class RoomChannel < ApplicationCable::Channel
    end
    

    Get the Redis adapter from ActionCable instead of creating it yourself (you'd need to supply the URL from config/cable.yml otherwise):

    pubsub = ActionCable.server.pubsub
    

    Get the channel's name including channel_prefix you may have specified in config/cable.yml:

    channel_with_prefix = pubsub.send(:channel_with_prefix, RoomChannel.channel_name)
    

    Get all connected channels from RoomChannel:

    # pubsub.send(:redis_connection) actually returns the Redis instance ActionCable uses
    channels = pubsub.send(:redis_connection).
      pubsub('channels', "#{channel_with_prefix}:*")
    

    Decode the subscription name:

    subscriptions = channels.map do |channel|
       Base64.decode64(channel.match(/^#{Regexp.escape(channel_with_prefix)}:(.*)$/)[1])
    end
    

    If you are subscribed to an ActiveRecord object, let's say Room (using stream_for), you can extract the IDs:

    # 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] }
    
    0 讨论(0)
  • 2020-12-10 03:26

    If using redis you can see all the pubsub channels.

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

    This will show all websocket connections for all the Puma workers together. And if you have multiple servers it will probably show those here too.

    0 讨论(0)
提交回复
热议问题