我们应该如何在 Rails 中配置 action cable 以在 Google App Engine 中工作?
我有一个 Rails 应用程序,它使用 action cable 作为它的信使。 在我的本地主机上,action cable 在开发和生产环境中运行良好,但它在 Google App Engine 上不起作用。
我创建了一个 Computer Engine 实例并在其上安装了 Redis。
防火墙允许所有流向 Redis 虚拟机的流量。
Redis 已绑定(bind) 0.0.0.0
当我在 Google App Engine 上部署应用程序时出现错误:
Firefox can’t establish a connection to the server at wss://mydomain.com/cable.
这是我当前的配置:
config/environments/production.rb
config.action_cable.url = 'wss://[MYDOMAIN].com/cable'
config.action_cable.disable_request_forgery_protection = true
config.force_ssl = true
...
config/cable.yml
production:
adapter: redis
url: redis://[IP_OF_REDIS_SERVER]:6379/
app.yaml
entrypoint: bundle exec rackup --port $PORT
env: flex
runtime: ruby
env_variables:
REDIS_PROVIDER: REDIS_URL
REDIS_URL: redis://[IP_OF_REDIS_SERVER]:6379/
SECRET_KEY_BASE: [My_Secret_Key]
我在 App Engine 的 Google 文档中找不到任何关于 actioncable 设置的信息。我希望这个问题可以帮助我和每个有同样问题的人。
最佳答案
您必须设置在 Redis 实例和 App Engine 实例之间创建一个 VPC。这记录在这里:
https://cloud.google.com/appengine/docs/standard/python/connecting-vpc
完成此操作后,您将拥有:
app.yaml
...
vpc_access_connector:
name: projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME
...
其次,Google 托管的 Redis 服务器不允许您设置客户端 ID。我试图强制它为零,但 ActionCable 订阅适配器会尝试为您设置一个:
为了让它正常工作,我不得不重写这个行为。
我将以下文件添加到我的 Rails 应用程序中:
config/initializers/decorators/redis.rb
require 'action_cable/subscription_adapter/redis'
ActionCable::SubscriptionAdapter::Redis.class_eval do
cattr_accessor :redis_connector, default: ->(config) do
::Redis.new(config.except(:id, :adapter, :channel_prefix))
end
end
现在一切正常。我现在唯一担心的是客户端 ID 在某种程度上是必需的,因此我最终会遇到一些讨厌的错误。
如果您尝试一下,希望这对您有用!
关于ruby-on-rails - Google App Engine + Ruby on rails + Redis + actioncable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51630864/