ActionCable的实例指南

109 阅读1分钟

ActionCable可以处理相当多的流量,但它已经到了可能成为服务器负担的地步。使用AnyCable,我们不仅可以处理更多的流量,还可以减轻资源。

# Terminal
rails g channel welcome

brew install anycable-go

anycable-go --host=localhost --port=3334
anycable

bundle exec anycable --server-command "anycable-go --host=localhost --port=3334"
# app/javascript/channels/welcome_channel.js
received(data) {
  // Called when there's incoming data on the websocket for this channel
  console.log(data)
}
  
# app/channels/welcome_channel.rb
def subscribed
  stream_from "welcome_channel"
end
# controllers/welcome_controller.rb
def index
  ActionCable.server.broadcast('welcome_channel', Time.now)
end
# Gemfile
gem "anycable-rails"
gem "redis"
# config/cable.yml
development:
  adapter: any_cable
# config/anycable.yml
development:
  redis_url: redis://localhost:6379/1
  access_logs_disabled: false
# config/environments/development.rb
config.action_cable.url = "ws://localhost:3334/cable"
# app/views/layouts/application.html.erb
<%= action_cable_meta_tag %>