网卡nat模式消息队列、数据库长连接不灵

网络连接模式是nat,连接不稳,我的一个amqp收queue脚本,客户端已断而服务器上显示仍连接,凭空吃message,数据库也经常断,所以写了一个bunny短连接版

#!/usr/bin/env ruby
require File.expand_path('../../config/environment', __FILE__)

def seek_queue
  queue_name = Settings.queue.packapp.ios

  BUNNY.start

  payload = BUNNY.queue(queue_name).pop[:payload]

  if payload == :queue_empty
    BUNNY.stop
    sleep 5
  else
    conn = ActiveRecord::Base.connection
    begin
      conn.reconnect! unless conn.active?
    rescue ActiveRecord::StatementInvalid => e
      sleep 10
      retry
    end

    # ...

    BUNNY.stop
  end
end

loop do

  begin 
    seek_queue
  rescue Bunny::ServerDownError => e
    sleep 10
    retry
  rescue Errno::ECONNRESET => e
    sleep 10
    retry
  end
  
end


ActiveRecord::StatementInvalid通常是数据库连接失效,捕获它重连数据库
rescue ActiveRecord::StatementInvalid => e
  error_logger ||= Logger.new(errlog_path)
  error_logger.fatal "#{Time.new} #{e.class}, retry"
  sleep 10
  ActiveRecord::Base.connection.reconnect!
  retry

你可能感兴趣的:(消息队列)