简体   繁体   English

Heroku Rails-关闭Active Record Postgres连接

[英]Heroku Rails - Turn off Active Record Postgres connection

I have a rails 4 app I am hosting on heroku. 我在heroku上托管了Rails 4应用程序。 They give some specific advice about how to manage your DB connection pool when using a multi-threaded server (puma) https://devcenter.heroku.com/articles/concurrency-and-database-connections 他们为使用多线程服务器(puma)时如何管理数据库连接池提供了一些具体建议。https://devcenter.heroku.com/articles/concurrency-and-database-connections

When I ran load testing for my app I got an error- can't connect to the db. 当我为我的应用程序执行负载测试时,出现错误-无法连接到数据库。 when each page was being hit, rails initializes active record, even if I'm not making any queries on that page, or referencing any models. 当每个页面都被点击时,Rails会初始化活动记录,即使我没有对该页面进行任何查询或引用任何模型也是如此。

My question is: 我的问题是:

How can I make a sort of whitelist (or blacklist) so that active record is not initialized with a db connection for these specific controller actions? 如何创建一种白名单(或黑名单),以便不使用这些特定控制器操作的数据库连接来初始化活动记录? In an initializer? 在初始化器中?

Ideally I would run the cheaper postgres service on heroku (40 connections) because I know my app doesnt use the db very often. 理想情况下,我会在heroku(40个连接)上运行便宜的postgres服务,因为我知道我的应用程序并不经常使用db。 If traffic hits higher that the 40 connections things will start to error, which seems silly for an app that wasn't going to use the db on those requests. 如果流量超过40个连接,一切将开始出错,这对于不打算在这些请求上使用db的应用程序来说似乎很愚蠢。

I read about how to disable active record for an entire app: Disable ActiveRecord for Rails 4 我阅读了有关如何为整个应用程序禁用活动记录的信息: 禁用ActiveRecord for Rails 4

But how do I selectively enable it? 但是如何有选择地启用它? Are there any other different performance considerations here (by not eager loading these things or any other gotchas) 这里是否还有其他不同的性能考虑因素(不急于加载这些东西或任何其他陷阱)

In you application_controller.rb 在你的application_controller.rb

before_filter :maybe_disconnect_db

def maybe_disconnect_db
  ActiveRecord::Base.remove_connection() if ActiveRecord::Base.connected?
end

def maybe_connect_db
  ActiveRecord::Base.establish_connection() unless ActiveRecord::Base.connected?
end

Then for each controller/action that needs the db connection add 然后为每个需要数据库连接的控制器/动作添加

skip_before_filter :maybe_disconnect_db, #only or unless filter here
before_filter      :maybe_connect_db,    #only or unless filter here

This should establish the connection for any specific db request, and disconnect for any request that doesn't need it, while also handling multiple db requests in a row without action, and multiple non db requests in a row without action. 这应该为任何特定的数据库请求建立连接,并为不需要此请求的任何请求断开连接,同时还可以连续执行多个db请求而不执行任何操作,并且连续处理多个非db请求而不执行任何操作。

ActiveRecord::Base.remove_connection ActiveRecord :: Base.remove_connection

ActiveRecord::Base.establish_connection ActiveRecord :: Base。Establishment_connection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM