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

idle connection in postgres causing process to stuck or result in error

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

这是我们注意到的。当我们的进程休眠时,我们的 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 会在一段时间后关闭空闲连接吗?

因为在下一个 运行 进程无法 insert/update DB.

中的任何记录

这是我的代码的样子。

  $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 进程永远卡住(不会死)。

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

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

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

正在配置postgresql.conf

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

tcp_keepalives_idle = 300

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