【问题标题】:idle connection in postgres causing process to stuck or result in errorpostgres 中的空闲连接导致进程卡住或导致错误
【发布时间】:2016-04-18 00:38:25
【问题描述】:

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

这是我们注意到的。当我们的进程处于休眠状态时,我们的 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 进程永远卡住了(不会死)。

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

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

【问题讨论】:

    标签: ruby postgresql activerecord jruby ruby-2.3


    【解决方案1】:

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

    配置postgresql.conf

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

    tcp_keepalives_idle = 300

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

    【讨论】:

    • 如果这是 keepalive 的问题,为什么我看不到任何超时,而且它在环回接口上工作得很好。我很确定环回连接通过 TCP socketnot unix socket 工作,因为我可以通过 tcpdump 通过 TCP 嗅探数据包.
    • 这是一个很好的答案,会建议检查 Java 套接字超时。无法解释为什么它使用 lo 起作用,但可能它以不同的方式处理 so-timeout。以前用 JRuby 看到过旧的 DB 连接套接字,虽然从来没有 localhost 所以如果你能确认测试并确认发生了什么(超时)会很有趣。
    猜你喜欢
    • 2011-11-02
    • 2022-12-18
    • 2022-06-11
    • 2016-09-16
    • 2019-04-19
    • 2021-05-27
    • 2016-07-11
    • 2013-01-20
    • 2018-08-07
    相关资源
    最近更新 更多