跳到内容 跳到搜索

Action Cable 服务器基础

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

此外,这是用于广播的服务器实例。有关更多信息,请参阅 Broadcasting

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

属性

[R] config
[R] mutex

类公共方法

logger()

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

new(config: self.class.config)

# File actioncable/lib/action_cable/server/base.rb, line 26
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 33
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 90
def connection_identifiers
  config.connection_class.call.identifiers
end

disconnect(identifiers)

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

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

event_loop()

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

pubsub()

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

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

remote_connections()

通往 RemoteConnections 的网关。有关详细信息,请参阅该类。

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

restart()

# File actioncable/lib/action_cable/server/base.rb, line 44
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 自行调整大小。

在频道操作中使用 ActiveRecord、Redis 等意味着你将从工作程序池中的每个线程获得一个单独的连接。相应地规划你的部署:每个运行 5 个 Puma 工作程序的 5 台服务器,每个运行 8 个线程的工作程序池,意味着至少 200 个数据库连接。

此外,确保你的数据库连接池大小至少与你的工作程序池大小一样大。否则,工作程序可能会过度订阅数据库连接池,并在等待其他工作程序释放其连接时阻塞。改用较小的工作程序池或较大的数据库连接池。

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