跳至内容 跳至搜索

Action Cable Server Base

可以通过 ActionCable.server 访问一个单例 ActionCable::Server 实例。它被启动 Action Cable 服务器的 Rack 进程所使用,用户也可以通过它访问 RemoteConnections 对象,该对象用于查找和断开所有服务器上的连接。

此外,它也是用于广播的服务器实例。更多信息请参见 Broadcasting

方法
C
D
E
L
N
P
R
W
包含的模块

Attributes

[R] config
[R] mutex

类公共方法

logger()

# File actioncable/lib/action_cable/server/base.rb, line 26
def self.logger; config.logger; end

new(config: self.class.config)

# File actioncable/lib/action_cable/server/base.rb, line 31
def initialize(config: self.class.config)
  @config = config
  @mutex = Monitor.new
  @remote_connections = @event_loop = @worker_pool = @pubsub = nil
end

实例公共方法

call(env)

由 Rack 调用以设置服务器。

# File actioncable/lib/action_cable/server/base.rb, line 38
def call(env)
  return config.health_check_application.call(env) if env["PATH_INFO"] == config.health_check_path
  setup_heartbeat_timer
  config.connection_class.call.new(self, env).process
end

connection_identifiers()

应用于此服务器关联的连接类的所有标识符。

# File actioncable/lib/action_cable/server/base.rb, line 102
def connection_identifiers
  config.connection_class.call.identifiers
end

disconnect(identifiers)

断开此服务器上或通过 RemoteConnections 提供的任何其他服务器上由 identifiers 标识的所有连接。

# File actioncable/lib/action_cable/server/base.rb, line 46
def disconnect(identifiers)
  remote_connections.where(identifiers).disconnect
end

event_loop()

# File actioncable/lib/action_cable/server/base.rb, line 71
def event_loop
  @event_loop || @mutex.synchronize { @event_loop ||= ActionCable::Connection::StreamEventLoop.new }
end

pubsub()

用于所有流/广播的适配器。

# File actioncable/lib/action_cable/server/base.rb, line 96
def pubsub
  @pubsub || @mutex.synchronize { @pubsub ||= config.pubsub_adapter.new(self) }
end

remote_connections()

RemoteConnections 的网关。详情请参见该类。

# File actioncable/lib/action_cable/server/base.rb, line 67
def remote_connections
  @remote_connections || @mutex.synchronize { @remote_connections ||= RemoteConnections.new(self) }
end

restart()

# File actioncable/lib/action_cable/server/base.rb, line 50
def restart
  connections.each do |connection|
    connection.close(reason: ActionCable::INTERNAL[:disconnect_reasons][:server_restart])
  end

  @mutex.synchronize do
    # Shutdown the worker pool
    @worker_pool.halt if @worker_pool
    @worker_pool = nil

    # Shutdown the pub/sub adapter
    @pubsub.shutdown if @pubsub
    @pubsub = nil
  end
end

worker_pool()

工作池是运行连接回调和频道操作的地方。我们在服务器的主线程上尽可能少地做事情。工作池是一个执行器服务,由一个工作线程池支持,这些线程从任务队列中处理任务。默认情况下,线程池的大小最多为 4 个工作线程。您可以使用 config.action_cable.worker_pool_size 来调整大小。

在您的频道操作中使用 Active Record、Redis 等意味着每个工作线程池中的线程都会获得一个单独的连接。请相应地规划您的部署:5 个服务器,每个服务器运行 5 个 Puma 工作进程,每个工作进程运行一个 8 线程的工作池,这意味着至少有 200 个数据库连接。

此外,请确保您的数据库连接池大小至少等于您的工作池大小。否则,工作进程可能会过度使用数据库连接池,并在等待其他工作进程释放其连接时阻塞。请改用较小的工作池或较大的数据库连接池。

# File actioncable/lib/action_cable/server/base.rb, line 91
def worker_pool
  @worker_pool || @mutex.synchronize { @worker_pool ||= ActionCable::Server::Worker.new(max_size: config.worker_pool_size) }
end