Rails 5 Actioncable - 失败:WebSocket 握手期间出错:意外响应代码:502

Rails 5 Actioncable - failed: Error during WebSocket handshake: Unexpected response code: 502

我正在尝试在 rails 5 中使用 ActionCable,但我不知道为什么它不起作用。

在浏览器控制台我收到:

WebSocket connection to 'ws://my.website/cable' failed: WebSocket is closed before the connection is established.

WebSocket connection to 'ws://my.website/cable' failed: Error during WebSocket handshake: Unexpected response code: 502

Uncaught TypeError: Cannot read property 'subscriptions' of undefined

我已经安装了 Passenger + Nginx

指南:https://www.phusionpassenger.com/library/install/nginx/install/oss/xenial/

sudo /usr/bin/passenger-config 验证安装:

* Checking whether this Passenger install is in PATH... ✓  
* Checking whether there are no other Passenger installations... ✓

sudo /usr/sbin/passenger-memory-stats:

Version: 5.1.4
Date   : 2017-06-14 10:05:30 +0000

------- Apache processes --------

### Processes: 0
### Total private dirty RSS: 0.00 MB


--------- Nginx processes ----------
PID   PPID  VMSize    Private  Name
------------------------------------
8176  1     142.8 MB  0.5 MB   nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
8179  8176  142.8 MB  0.7 MB   nginx: worker process
### Processes: 2
### Total private dirty RSS: 1.22 MB


---- Passenger processes -----
PID   VMSize    Private  Name
------------------------------
8156  421.3 MB  1.1 MB   Passenger watchdog
8159  636.5 MB  1.7 MB   Passenger core
8165  429.6 MB  1.2 MB   Passenger ust-router
### Processes: 3
### Total private dirty RSS: 4.07 MB

由于本指南,我拥有带 Passenger + Nginx 的 Integrated Action Cable:Integrating Action Cable with Passenger + Nginx

所以 nginx + passenger 运行 以及 app 已上线。

我的 rails 应用程序名称是 "final"

/opt/nginx/config/nginx.config:(在 http {...} 内)

        user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;
server {
    listen       80;
    server_name  my.website www.my.website;
    rails_env production;


root /var/www/final/public;
passenger_enabled on;
passenger_app_root   /var/www/final;        







location /cable {
    passenger_app_group_name final_websocket;
    passenger_force_max_concurrent_requests_per_process 0;

}

      }

final/config/routes.rb: mount ActionCable.server => '/cable'

另外我在application.html.erb

里面添加了<%= action_cable_meta_tag %>

final/config/cable.yml:

production: &production
  url: redis://localhost:6379

少log/production.log:

I, [2017-06-14T11:55:49.841674 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1]   Rendering account/seting.html.erb within layouts/application
I, [2017-06-14T11:55:49.842952 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1]   Rendered account/_header.html.erb (1.0ms) [cache miss]
I, [2017-06-14T11:55:50.469493 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1]   Rendered account/_footer.html.erb (0.5ms) [cache miss]
I, [2017-06-14T11:55:50.469629 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1]   Rendered account/seting.html.erb within layouts/application (627.9ms)
I, [2017-06-14T11:55:50.470586 #7666]  INFO -- : [7b1f4cd9-5fbf-44f5-ba77-e4d7dc40c8f1] Completed 200 OK in 633ms (Views: 629.2ms | ActiveRecord: 0.4ms)
I, [2017-06-14T11:55:51.024845 #7709]  INFO -- : [2c674f25-f747-4cbc-9ad8-b6f517bd5b72] Started GET "/cable" for 213.7.71.70 at 2017-06-14 11:55:51 +0000
I, [2017-06-14T11:55:51.062689 #7709]  INFO -- : [2c674f25-f747-4cbc-9ad8-b6f517bd5b72] Started GET "/cable/" [WebSocket] for 213.7.71.70 at 2017-06-14 11:55:51 +0000
I, [2017-06-14T11:55:51.062890 #7709]  INFO -- : [2c674f25-f747-4cbc-9ad8-b6f517bd5b72] Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: upgrade, HTTP_UPGRADE: websocket)
D, [2017-06-14T11:55:51.081839 #7709] DEBUG -- :   ESC[1mESC[35m (0.5ms)ESC[0m  ESC[1mESC[35mSET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), log/production.log

enviroment/production.rb:

   config.action_cable.url = "/cable"  
   config.action_cable.allowed_request_origins = [ 'http://my-server-ip-address', /http:\/\/example.*/ ]

在 rails 控制台中- ActionCable.server.config:

=> #<ActionCable::Server::Configuration:0x007f9ec2027598 @log_tags=[], @connection_class=#<Proc:0x007f9ec20224a8@/usr/local/lib/ruby/gems/2.4.0/gems/actioncable-5.1.1/lib/action_ca
ble/engine.rb:35 (lambda)>, @worker_pool_size=4, @disable_request_forgery_protection=false, @allow_same_origin_as_host=true, @logger=#<ActiveSupport::Logger:0x007f9ec3242c28 @level
=0, @progname=nil, @default_formatter=#<Logger::Formatter:0x007f9ec3242b60 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x007f9ec3242a48 @datetime_for
mat=nil, @thread_key="activesupport_tagged_logging_tags:70159927743780">, @logdev=#<Logger::LogDevice:0x007f9ec3242b10 @shift_period_suffix=nil, @shift_size=nil, @shift_age=nil, @f
ilename=nil, @dev=#<IO:/dev/pts/2>, @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x007f9ec3242a98>>, @local_levels=#<Concurrent::Map:0x007f9ec32429d0 entries=0 default_
proc=nil>>, @cable={"adapter"=>"redis", "url"=>"redis://localhost:6379"}, @mount_path="/cable", @url="/cable", @allowed_request_origins=["http://my.website"]>

assets/javascripts/cable.js:

// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer('/cable');

}).call(this);

channels/application_cable/connection.rb:

module ApplicationCable
  class Connection < ActionCable::Connection::Base


    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private
      def find_verified_user
        if verified_user = User.find_by(id: cookies.signed[:user_id])
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end

var/log/nginx/error.log:

[ 2017-06-14 12:46:00.0110 14157/7f41c30e9700 age/Cor/App/Poo/AnalyticsCollection.cpp:102 ]: Process (pid=15020, group=final_websocket) no longer exists! Detaching it from the pool.
[ 2017-06-14 12:46:00.0132 14157/7f41c30e9700 age/Cor/CoreMain.cpp:907 ]: Checking whether to disconnect long-running connections for process 15020, application final_websocket
App 15037 stdout: 
App 14181 stderr: /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/connection/ruby.rb:229:in `getaddrinfo': getaddrinfo: Name or service not known (SocketError)
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/connection/ruby.rb:229:in `connect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/connection/ruby.rb:313:in `connect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:336:in `establish_connection'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:101:in `block in connect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:293:in `with_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:100:in `connect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:276:in `with_socket_timeout'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:133:in `call_loop'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/subscribe.rb:43:in `subscription'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/subscribe.rb:12:in `subscribe'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:2765:in `_subscription'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:2143:in `block in subscribe'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:58:in `block in synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:58:in `synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:2142:in `subscribe'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/actioncable-5.1.1/lib/action_cable/subscription_adapter/redis.rb:77:in `block in listen'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis/client.rb:293:in `with_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:64:in `block in with_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:58:in `block in synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:58:in `synchronize'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:63:in `with_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/redis-3.3.3/lib/redis.rb:70:in `without_reconnect'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/actioncable-5.1.1/lib/action_cable/subscription_adapter/redis.rb:74:in `listen'
App 14181 stderr:   from /usr/local/lib/ruby/gems/2.4.0/gems/actioncable-5.1.1/lib/action_cable/subscription_adapter/redis.rb:148:in `block in ensure_listener_running'

这里有两个问题: 1. cable.js应该是这个

:`// app/assets/javascripts/cable.js
//= require action_cable
//= require_self
//= require_tree ./channels
(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();
}).call(this);`
  1. 我在 nginx.conf 中评论了这一行:#include /etc/nginx/sites-enabled/*; 因为文件 sites-enabled/default 中的配置与 nginx.conf
  2. 中的配置重叠

我希望这个问题和答案可以节省一些人的时间。