private CountDownLatch prepareForShutdown(Connection conn) throws InterruptedException {
   final CountDownLatch latch = new CountDownLatch(1);
   conn.addShutdownListener(
       new ShutdownListener() {
         public void shutdownCompleted(ShutdownSignalException cause) {
           latch.countDown();
         }
       });
   return latch;
 }
 private Connection createConnection() throws IOException {
   Connection connection = connectionFactory.newConnection();
   connection.addShutdownListener(
       new ShutdownListener() {
         @Override
         public void shutdownCompleted(ShutdownSignalException cause) {
           logger.error("shutdown signal received", cause);
           reporter.reportError(cause);
           reset();
         }
       });
   logger.info("connected to rabbitmq: " + connection + " for " + queueName);
   return connection;
 }
Example #3
0
  public void connect() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostname);
    factory.setPort(port);

    // Authenticate?
    if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
      factory.setUsername(username);
      factory.setPassword(password);
    }

    connection = factory.newConnection();
    channel = connection.createChannel();

    if (prefetchCount > 0) {
      channel.basicQos(prefetchCount);

      LOG.info("AMQP prefetch count overriden to <{}>.", prefetchCount);
    }

    connection.addShutdownListener(
        new ShutdownListener() {
          @Override
          public void shutdownCompleted(ShutdownSignalException cause) {
            while (true) {
              try {
                LOG.error("AMQP connection lost! Trying reconnect in 1 second.");

                Thread.sleep(1000);

                connect();

                LOG.info("Connected! Re-starting consumer.");

                run();

                LOG.info("Consumer running.");
                break;
              } catch (IOException e) {
                LOG.error("Could not re-connect to AMQP broker.", e);
              } catch (InterruptedException ignored) {
              }
            }
          }
        });
  }
Example #4
0
  private Connection _newConnection(int numThreads) throws IOException {
    ConnectionFactory connFactory = new ConnectionFactory();
    ThreadFactory threadFactory = DaemonThreadFactory.getInstance("RabbitMQ-ConsumerThread", true);
    final ExecutorService executor = Executors.newFixedThreadPool(numThreads, threadFactory);
    Address[] array = addresses.toArray(new Address[0]);
    Connection conn = connFactory.newConnection(executor, array);

    conn.addShutdownListener(
        new ShutdownListener() {
          @Override
          public void shutdownCompleted(ShutdownSignalException sse) {
            executor.shutdown();
          }
        });

    return conn;
  }