code

활성 레코드:: 접속TimeoutError: 5.000초(대기 5.000초) 내에 데이터베이스 연결을 가져올 수 없습니다.

starcafe 2023. 9. 20. 20:36
반응형

활성 레코드:: 접속TimeoutError: 5.000초(대기 5.000초) 내에 데이터베이스 연결을 가져올 수 없습니다.

생산 중인 레일 앱이 있는데 요전에 몇 가지 변경 사항을 배포했습니다.갑자기 오류가 납니다.ActiveRecord::ConnectionTimeoutError: could not obtain a database connection within 5.000 seconds (waited 5.000 seconds)하루에 여러번 푸마를 다시 시작해야 문제를 해결할 수 있습니다.

저는 이것의 원인이 무엇인지 완전히 난처합니다.서버에서 아무것도 변경하지 않았고 변경한 내용은 매우 간단했습니다(보기에 추가하고 컨트롤러 방법에 추가).

로그 파일에는 아무것도 보이지 않습니다.

레일 4.1.4와 루비 2.0.0p481을 사용하고 있습니다.

왜 내 연줄이 채워지는지에 대한 아이디어가 있습니까?내 연결 풀은 10으로 설정되어 있고 기본 퓨마 구성을 사용하고 있습니다.

스택 트레이스는 다음과 같습니다.

ActiveRecord::ConnectionTimeoutError (could not obtain a database connection within 5.000 seconds (waited 5.000 seconds)):
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:190:in `block in wait_poll'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:181:in `loop'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:181:in `wait_poll'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:136:in `block in poll'
  /usr/local/rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:146:in `synchronize'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:134:in `poll'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:418:in `acquire_connection'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:351:in `block in checkout'
  /usr/local/rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:350:in `checkout'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:265:in `block in connection'
  /usr/local/rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:264:in `connection'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:541:in `retrieve_connection'
  activerecord (4.1.4) lib/active_record/connection_handling.rb:113:in `retrieve_connection'
  activerecord (4.1.4) lib/active_record/connection_handling.rb:87:in `connection'
  activerecord (4.1.4) lib/active_record/query_cache.rb:51:in `restore_query_cache_settings'
  activerecord (4.1.4) lib/active_record/query_cache.rb:43:in `rescue in call'
  activerecord (4.1.4) lib/active_record/query_cache.rb:32:in `call'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:82:in `run_callbacks'
  actionpack (4.1.4) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  airbrake (4.1.0) lib/airbrake/rails/middleware.rb:13:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.1.4) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.1.4) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.1.4) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  dragonfly (1.0.5) lib/dragonfly/cookie_monster.rb:9:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.1.4) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  airbrake (4.1.0) lib/airbrake/user_informer.rb:16:in `_call'
  airbrake (4.1.0) lib/airbrake/user_informer.rb:12:in `call'
  railties (4.1.4) lib/rails/engine.rb:514:in `call'
  railties (4.1.4) lib/rails/application.rb:144:in `call'
  railties (4.1.4) lib/rails/railtie.rb:194:in `public_send'
  railties (4.1.4) lib/rails/railtie.rb:194:in `method_missing'
  puma (2.9.0) lib/puma/configuration.rb:71:in `call'
  puma (2.9.0) lib/puma/server.rb:490:in `handle_request'
  puma (2.9.0) lib/puma/server.rb:361:in `process_client'
  puma (2.9.0) lib/puma/server.rb:254:in `block in run'
  puma (2.9.0) lib/puma/thread_pool.rb:92:in `call'
  puma (2.9.0) lib/puma/thread_pool.rb:92:in `block in spawn_thread'

퓨마 init.d 스크립트

#!/bin/sh
# Starts and stops puma
#


case "$1" in
        start)
                su myuser -c  "source /etc/profile && cd /var/www/myapp/current && rvm gemset use myapp && puma -d -e production -b unix:///var/www/myapp/myapp_app.sock -S /var/www/myapp/myapp_app.state"
        ;;

        stop)
                su myuser -c "source /etc/profile && cd /var/www/myapp/current &&  rvm gemset use myapp && RAILS_ENV=production bundle exec pumactl -S /var/www/myapp/myapp_app.state stop"
        ;;

        restart)
                $0 stop
                $0 start
        ;;

        *)
                echo "Usage: $0 {start|stop|restart}"
                exit 1
esac

편집

저는 마침내 그 문제를 좁힌 것 같습니다. 와 함께 에어브레이크 보석과 디바이즈 방법으로current_user아니면user_signed_in?인에application_controller.rb일순간에before_action.

애플리케이션 컨트롤러는 다음과 같습니다.

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :authenticate_user!, :get_new_messages 

  # Gets the unread messages for the logged in user
  def get_new_messages
    @num_new_messages = 0 # Initially set to 0 so login page, etc works
    # If the user is signed in, fetch the new messages
    if user_signed_in? # I also tried !current_user.nil?
      @num_new_messages = Message.where(:created_for => current_user.id).where(:viewed => false).count
    end
  end

...
end

제거하면.if블록, 나는 아무 문제가 없습니다.제가 그 코드를 도입한 이후로 제 앱은 연결이 다 된 것 같습니다.그것을 떠나면if제자리에서 차단하고 에어브레이크 보석을 제거합니다. 앱은 기본 5개의 연결만 설정하면 정상적으로 실행되는 것 같습니다.database.yml파일.

편집

내가 이 대사를 언급하면 나는 마침내 그것을 알게 됩니다.config/environments/production.rb파일config.exceptions_app = self.routes내가 실수를 하지 않을 거라고요.사용자 지정 경로 + 조치 전 앱 컨트롤러에서 디바이즈 하는 것이 원인인 것 같습니다.github에서 이슈와 재현 가능한 프로젝트를 만들었습니다.

https://github.com/plataformatec/devise/issues/3422 https://github.com/toymachiner62/devise-connection-failure/blob/master/config/environments/production.rb#L84

데이터베이스에 너무 많은 개방형 연결로 인해 발생한 동일한 문제가 있었습니다.이 문제는 컨트롤러 외부(모델, 메일러, pdf 생성기 등)에 데이터베이스 쿼리가 있을 때 발생할 수 있습니다.

저는 자동으로 연결이 닫히는 이 블록에 쿼리를 래핑하여 수정할 수 있었습니다.

ActiveRecord::Base.connection_pool.with_connection do
  # your code
end

Puma는 멀티 스레드로 작동하기 때문에 풀 크기(Abraham이 언급한 바와 같이)도 제한이 될 수 있습니다.좀 더 늘려보세요.

도움이 됐으면 좋겠네요!

고안자들의 도움으로 드디어 이 문제를 해결한 것 같습니다. 지정 다 before_action것 .get_new_messages 매우 은 다음을 따라서 매우 간단한 해결책은 다음을 추가하는 것이었습니다.

skip_before_filter :get_new_messages

사용자 지정 오류 컨트롤러로 이동합니다.

이 문제는 이 문제의 배경을 자세히 설명합니다. https://github.com/plataformatec/devise/issues/3422

결국 이 문제는 1년 정도 더 저를 괴롭혔습니다.드디어 퓨마들과 함께 일해서 좋은 해결책을 얻었습니다.

다음으로 합니다.2.15.x.

언급URL : https://stackoverflow.com/questions/27801185/activerecordconnectiontimeouterror-could-not-obtain-a-database-connection-wit

반응형