ruby - postgres 中的空闲连接导致进程卡住或导致错误

标签 ruby postgresql activerecord jruby ruby-2.3

我们将 Postgres 作为后端数据库。我们的进程运行一些工作(即它在数据库中执行一些插入/更新)然后休眠一个小时

这是我们注意到的。当我们的进程处于 sleep 状态时,我们的 Postgres 连接状态被视为空闲。

postgres  5045  0.3  0.4 231220 33780 ?        Ss   12:13   0:16 postgres: scp scp_test x.x.x.x(60400) idle    

现在我的问题是?

如果,我有一个进程休眠一个小时

Postgres 会在一段时间后关闭空闲连接吗?

因为在下一次运行过程中无法插入/更新数据库中的任何记录

这是我的代码的样子。

  $logger  = Logger.new('log/checker.log')
  last_modified = Time.now
  while
    if (last_modified == File.mtime(file_path))
      $logger.info "Sleeping for 1 hour"
      sleep 3600
    else
      $logger.info "Inserting the file mtime changed .."
      last_modified = File.mtime(file_path)
      $logger.info "File modified ....."
      attributes = Test.testFile(file_path)
      index = 0 
      $logger.info "........Index set......"
      header_attributes = attributes.shift
      $logger.info "...........Header removed..........."
      trailer_attributes = attributes.pop
      $logger.info "...Trailer removed......."
      count = attributes.count
      $logger.info "............Count calculated #{count} ........."
      attributes.each_slice(50000) { |records|
        _records = initialize_records(records)
        _records.each { |record| 
          record.save 
          index += 1 
          $logger.info "Inserting ...... [#{index}/#{count}]"
       }
     }
     $logger.info "Completed insertion of #{count}" 
   end
 end

测试了这个
Ruby-2.2.2  -  ActiveRecord-4.2.6  - pg-0.18.0 
Ruby-2.3.0  -  ActiveRecord-4.2.6  - pg-0.18.0  
Jruby-9.0.5.0 - ActiveRecord-4.2.6 - activerecord-jdbc-adapter

Postgres 版本。

 PostgreSQL 9.4.5 on x86_64-unknown-linux-gnu, compiled by gcc (Debian 4.9.2-10) 4.9.2, 64-bit
(1 row)

Ruby 和 JRuby 的输出有 1 个区别吗?

虽然两个进程从休眠中醒来后都卡住了

Ruby 进程死于 PG::UnableToSend: SSL SYSCALL error: EOF detected 错误

但是 JRuby 进程会永远卡住(不会死)。

不确定问题出在哪里,因为此时我无法确定任何特定的库或代码。

注意:在环回接口(interface)上工作得很好。有问题的 postgres 服务器是远程服务器..

最佳答案

数据文件夹内有一个名为postgresql.conf 的文件,您必须将其配置为向客户端发送keepalive 消息。阅读this了解更多信息。

配置 postgresql.conf

您的 postgresql.conf 文件应该有这样一行 tcp_keepalives_idle。 如果您想每 5 分钟向客户端计算机发送一次 keepalive 消息;像这样更新 tcp_keepalives_idle

tcp_keepalives_idle = 300

确保通过删除 # 标记取消对该行的注释。

关于ruby - postgres 中的空闲连接导致进程卡住或导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36677580/

相关文章:

sql - 通过 PostgreSQL 为数据库中的列设置默认值

django - 模板语法错误 : Caught ImportError while rendering: cannot import name utils

ruby-on-rails - 如何从 Rails 中的 'first' 或 'last' 记录中获取属性值?

ruby-on-rails - Ruby Gem ActiveRecord 具有多个条件的查找方法

ruby - 用于抓取城市、州、 zip 的正则表达式

ruby - Padrino 和 RSpec 不适用于 Sequel?

sql - 如何使用 Mysqldump for Postgres 格式更改单引号的转义?

ruby-on-rails - Rails 中的分组和求和

ruby-on-rails - ruby on rails 和 mongo

ruby - Nokogiri to_xhtml 将 doctype 放在 <?xml 之前