public void processFollowings() {
    while (true) {
      QueueingConsumer.Delivery delivery;
      try {
        delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        Long tag = delivery.getEnvelope().getDeliveryTag();

        String[] split = message.split(" ");
        Long followerVkId = Long.valueOf(split[0]);
        Long followingVkId = Long.valueOf(split[1]);

        Follower follower = dbService.getFollowerByVkId(followerVkId);
        Following following = follower.getFollowingByVkId(followingVkId);

        refreshFollowing(follower, following);

        channel.basicAck(tag, false);
        System.out.println("Ok");
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #2
0
  public static void t1() throws Exception {
    Channel channel = generateChannel();
    // channel.exchangeDeclare(TestAmqp.ExchangerName, "direct", true, false, null);
    // channel.exchangeDeclare(TestAmqp.FanoutExchangerName, "fanout", true, false, null);
    channel.exchangeDeclare(TestAmqp.TopicExchangerName, "topic", false, false, null);
    channel.queueDeclare(TestAmqp.TopicQueueName, false, false, false, null);
    // channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName,
    // TestAmqp.RouteingName);
    // channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName, "*");
    channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName, "#.*");

    // channel.basicPublish(TestAmqp.ExchangerName, TestAmqp.RouteingName, null, "haha".getBytes());

    QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

    channel.basicQos(1);
    channel.basicConsume(TestAmqp.TopicQueueName, queueingConsumer);

    while (true) {
      QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
      System.out.println(new String(delivery.getBody()));

      long deliveryTag = delivery.getEnvelope().getDeliveryTag();
      System.out.println("start basicAck:" + deliveryTag);
      // if (true)throw new RuntimeException("xxxxx");
      channel.basicAck(deliveryTag, false);
    }

    // channel.close();
    // connection.close();
  }
Beispiel #3
0
  private void consumeMessages() {
    while (true) {
      QueueingConsumer.Delivery delivery;

      try {
        delivery = consumer.nextDelivery();

        final String message = new String(delivery.getBody());

        runOnUiThread(
            new Runnable() {
              public void run() {
                Toast.makeText(ReceiveActivity.this, message, Toast.LENGTH_LONG).show();
              }
            });

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

      } catch (ShutdownSignalException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      } catch (ConsumerCancelledException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Beispiel #4
0
  public static void main(String[] args) throws IOException, InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    boolean durable = true;
    channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
    System.out.println("[*] waiting for messages.To exit press ctrl+z");

    // 公平分发
    // 告知RabbitMQ不要同时给一个工作者超过一个任务
    // 1个工作者处理完成,发送确认之前不要给它分发一个新的消息
    int prefetchcount = 1;
    channel.basicQos(prefetchcount);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    boolean autoAck = false;
    channel.basicConsume(QUEUE_NAME, false, consumer);

    while (true) {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery();
      String message = new String(delivery.getBody());
      System.out.println(" [x] Received '" + message + "'");
      // 模拟工作
      doWork(message);
      System.out.println(" [x] Done");
      // 发送确认消息
      channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
  }
Beispiel #5
0
  public static void main(String[] args) throws Exception {
    // 获取到连接以及mq通道
    Connection connection = ConnectionUtil.getConnection();
    Channel channel = connection.createChannel();

    // 声明队列
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    // 绑定队列到交换机
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "#.#");

    // 同一时刻服务器只会发一条消息给消费者
    channel.basicQos(1);

    // 定义队列的消费者
    QueueingConsumer consumer = new QueueingConsumer(channel);
    // 监听队列,手动返回完成
    channel.basicConsume(QUEUE_NAME, false, consumer);

    // 获取消息
    while (true) {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery();
      String message = new String(delivery.getBody());
      System.out.println(" [x] Received '" + message + "'");
      Thread.sleep(10);
      channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
  }
 public void ack(Long msgId) {
   try {
     channel.basicAck(msgId, false);
   } catch (Exception e) {
     logger.error("could not ack for msgId: " + msgId, e);
     reporter.reportError(e);
   }
 }
Beispiel #7
0
 public void ack(Object msgId) {
   System.out.println("Acking msg: " + msgId);
   if (msgId instanceof Long) {
     final long deliveryTag = (Long) msgId;
     if (amqpChannel != null) {
       try {
         amqpChannel.basicAck(deliveryTag, false /* not multiple */);
       } catch (IOException e) {
         log.warn("Failed to ack delivery-tag " + deliveryTag, e);
       }
     }
   } else {
     log.warn(String.format("don't know how to ack(%s: %s)", msgId.getClass().getName(), msgId));
   }
 }
Beispiel #8
0
  public void run() {
    System.out.println(" [x] Awaiting RPC requests");

    while (run.get()) {

      QueueingConsumer.Delivery delivery;
      try {
        delivery = consumer.nextDelivery(2000);
      } catch (ShutdownSignalException e2) {
        break;
      } catch (ConsumerCancelledException e2) {
        break;
      } catch (InterruptedException e2) {
        continue;
      }

      BasicProperties props = delivery.getProperties();
      BasicProperties replyProps =
          new BasicProperties.Builder().correlationId(props.getCorrelationId()).build();

      try {
        Object o;
        synchronized (registry) {
          o = Rmivm.deserialise(delivery.getBody(), registry);
        }

        byte[] outBytes = Rmivm.serialize(o);

        synchronized (channel) {
          channel.basicPublish("", props.getReplyTo(), replyProps, outBytes);
          channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }

      } catch (Exception e) {
        try {
          synchronized (channel) {
            channel.basicPublish(
                "", props.getReplyTo(), replyProps, Rmivm.serialize(new Exception("Boom!")));
          }

        } catch (IOException e1) {
          // panic
        }
      }
    }

    System.out.println(" [x] Shutting Down");
  }
Beispiel #9
0
 /** Acks the message with the AMQP broker. */
 @Override
 public void ack(Object msgId) {
   if (msgId instanceof Long) {
     final long deliveryTag = (Long) msgId;
     if (amqpChannel != null) {
       try {
         amqpChannel.basicAck(deliveryTag, false /* not multiple */);
       } catch (IOException e) {
         log.warn("Failed to ack delivery-tag " + deliveryTag, e);
       } catch (ShutdownSignalException e) {
         log.warn("AMQP connection failed. Failed to ack delivery-tag " + deliveryTag, e);
       }
     }
   } else {
     log.warn(String.format("don't know how to ack(%s: %s)", msgId.getClass().getName(), msgId));
   }
 }
Beispiel #10
0
  public void serveRequests() {
    while (true) {
      try {

        Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        System.out.println("Received API call...replying...");

        channel.basicPublish("", props.getReplyTo(), null, getResponse(delivery).getBytes("UTF-8"));

      } catch (Exception e) {
        System.out.println(e.toString());
      }
    }
  }
Beispiel #11
0
  public static void t3() throws Exception {
    Channel channel = generateChannel();
    channel.exchangeDeclare(TestAmqp.PingExchangerName, "direct", true, false, null);
    channel.queueDeclare("rpc", false, false, false, null);
    // channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName,
    // TestAmqp.RouteingName);
    // channel.queueBind(TestAmqp.TopicQueueName, TestAmqp.TopicExchangerName, "*");
    channel.queueBind("rpc", TestAmqp.PingExchangerName, "ping");

    QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
    channel.basicConsume("rpc", false, queueingConsumer);

    while (true) {
      QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
      System.out.println("log: " + new String(delivery.getBody()));
      channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

      System.out.println("reply to :" + delivery.getProperties().getReplyTo());
      channel.basicPublish("", delivery.getProperties().getReplyTo(), null, "asfasdfas".getBytes());
    }
  }
Beispiel #12
0
  public static void t2() throws Exception {
    Channel channel = generateChannel();
    AMQP.Queue.DeclareOk declareOk1 = channel.queueDeclare();
    AMQP.Queue.DeclareOk declareOk2 = channel.queueDeclare();
    AMQP.Queue.DeclareOk declareOk3 = channel.queueDeclare();

    String exchange = "amq.rabbitmq.log";
    channel.queueBind(declareOk1.getQueue(), exchange, "error");
    channel.queueBind(declareOk2.getQueue(), exchange, "waring");
    channel.queueBind(declareOk3.getQueue(), exchange, "info");

    QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
    channel.basicConsume(declareOk1.getQueue(), false, queueingConsumer);
    channel.basicConsume(declareOk2.getQueue(), false, queueingConsumer);
    channel.basicConsume(declareOk3.getQueue(), false, queueingConsumer);

    while (true) {
      QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
      System.out.println("log: " + new String(delivery.getBody()));
      channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
  }
  public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("q", "queue", true, "queue name"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("k", "routing-key", true, "routing key"));
    options.addOption(new Option("d", "directory", true, "output directory"));

    CommandLineParser parser = new GnuParser();

    try {
      CommandLine cmd = parser.parse(options, args);

      String uri = strArg(cmd, 'h', "amqp://localhost");
      String requestedQueueName = strArg(cmd, 'q', "");
      String exchangeType = strArg(cmd, 't', "direct");
      String exchange = strArg(cmd, 'e', null);
      String routingKey = strArg(cmd, 'k', null);
      String outputDirName = strArg(cmd, 'd', ".");

      File outputDir = new File(outputDirName);
      if (!outputDir.exists() || !outputDir.isDirectory()) {
        System.err.println("Output directory must exist, and must be a directory.");
        System.exit(2);
      }

      ConnectionFactory connFactory = new ConnectionFactory();
      connFactory.setUri(uri);
      Connection conn = connFactory.newConnection();

      final Channel ch = conn.createChannel();

      String queueName =
          (requestedQueueName.equals("")
                  ? ch.queueDeclare()
                  : ch.queueDeclare(requestedQueueName, false, false, false, null))
              .getQueue();

      if (exchange != null || routingKey != null) {
        if (exchange == null) {
          System.err.println("Please supply exchange name to bind to (-e)");
          System.exit(2);
        }
        if (routingKey == null) {
          System.err.println("Please supply routing key pattern to bind to (-k)");
          System.exit(2);
        }
        ch.exchangeDeclare(exchange, exchangeType);
        ch.queueBind(queueName, exchange, routingKey);
      }

      QueueingConsumer consumer = new QueueingConsumer(ch);
      ch.basicConsume(queueName, consumer);
      while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        Map<String, Object> headers = delivery.getProperties().getHeaders();
        byte[] body = delivery.getBody();
        Object headerFilenameO = headers.get("filename");
        String headerFilename =
            (headerFilenameO == null) ? UUID.randomUUID().toString() : headerFilenameO.toString();
        File givenName = new File(headerFilename);
        if (givenName.getName().equals("")) {
          System.out.println("Skipping file with empty name: " + givenName);
        } else {
          File f = new File(outputDir, givenName.getName());
          System.out.print("Writing " + f + " ...");
          FileOutputStream o = new FileOutputStream(f);
          o.write(body);
          o.close();
          System.out.println(" done.");
        }
        ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
      }
    } catch (Exception ex) {
      System.err.println("Main thread caught exception: " + ex);
      ex.printStackTrace();
      System.exit(1);
    }
  }
    @Override
    public void run() {
      while (true) {
        if (closed) {
          break;
        }
        try {
          connection = connectionFactory.newConnection(rabbitAddresses);
          channel = connection.createChannel();
        } catch (Exception e) {
          if (!closed) {
            logger.warn("failed to created a connection / channel", e);
          } else {
            continue;
          }
          cleanup(0, "failed to connect");
          try {
            Thread.sleep(5000);
          } catch (InterruptedException e1) {
            // ignore, if we are closing, we will exit later
          }
        }

        QueueingConsumer consumer = null;
        // define the queue
        try {
          if (rabbitQueueDeclare) {
            // only declare the queue if we should
            channel.queueDeclare(
                rabbitQueue /*queue*/,
                rabbitQueueDurable /*durable*/,
                false /*exclusive*/,
                rabbitQueueAutoDelete /*autoDelete*/,
                rabbitQueueArgs /*extra args*/);
          }
          if (rabbitExchangeDeclare) {
            // only declare the exchange if we should
            channel.exchangeDeclare(
                rabbitExchange /*exchange*/, rabbitExchangeType /*type*/, rabbitExchangeDurable);
          }

          channel.basicQos(
              rabbitQosPrefetchSize /*qos_prefetch_size*/,
              rabbitQosPrefetchCount /*qos_prefetch_count*/,
              false);

          if (rabbitQueueBind) {
            // only bind queue if we should
            channel.queueBind(
                rabbitQueue /*queue*/,
                rabbitExchange /*exchange*/,
                rabbitRoutingKey /*routingKey*/);
          }
          consumer = new QueueingConsumer(channel);
          channel.basicConsume(rabbitQueue /*queue*/, false /*noAck*/, consumer);
        } catch (Exception e) {
          if (!closed) {
            logger.warn("failed to create queue [{}]", e, rabbitQueue);
          }
          cleanup(0, "failed to create queue");
          continue;
        }

        // now use the queue to listen for messages
        while (true) {
          if (closed) {
            break;
          }
          QueueingConsumer.Delivery task;
          try {
            task = consumer.nextDelivery();
          } catch (Exception e) {
            if (!closed) {
              logger.error("failed to get next message, reconnecting...", e);
            }
            cleanup(0, "failed to get message");
            break;
          }

          if (task != null && task.getBody() != null) {
            final List<Long> deliveryTags = Lists.newArrayList();

            BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();

            try {
              processBody(task, bulkRequestBuilder);
            } catch (Exception e) {
              logger.warn(
                  "failed to parse request for delivery tag [{}], ack'ing...",
                  e,
                  task.getEnvelope().getDeliveryTag());
              try {
                channel.basicAck(task.getEnvelope().getDeliveryTag(), false);
              } catch (IOException e1) {
                logger.warn("failed to ack [{}]", e1, task.getEnvelope().getDeliveryTag());
              }
              continue;
            }

            deliveryTags.add(task.getEnvelope().getDeliveryTag());

            if (bulkRequestBuilder.numberOfActions() < bulkSize) {
              // try and spin some more of those without timeout, so we have a bigger bulk (bounded
              // by the bulk size)
              try {
                while ((task = consumer.nextDelivery(bulkTimeout.millis())) != null) {
                  try {
                    processBody(task, bulkRequestBuilder);
                    deliveryTags.add(task.getEnvelope().getDeliveryTag());
                  } catch (Throwable e) {
                    logger.warn(
                        "failed to parse request for delivery tag [{}], ack'ing...",
                        e,
                        task.getEnvelope().getDeliveryTag());
                    try {
                      channel.basicAck(task.getEnvelope().getDeliveryTag(), false);
                    } catch (Exception e1) {
                      logger.warn(
                          "failed to ack on failure [{}]", e1, task.getEnvelope().getDeliveryTag());
                    }
                  }
                  if (bulkRequestBuilder.numberOfActions() >= bulkSize) {
                    break;
                  }
                }
              } catch (InterruptedException e) {
                if (closed) {
                  break;
                }
              } catch (ShutdownSignalException sse) {
                logger.warn(
                    "Received a shutdown signal! initiatedByApplication: [{}], hard error: [{}]",
                    sse,
                    sse.isInitiatedByApplication(),
                    sse.isHardError());
                if (!closed && sse.isInitiatedByApplication()) {
                  logger.error("failed to get next message, reconnecting...", sse);
                }
                cleanup(0, "failed to get message");
                break;
              }
            }

            if (logger.isTraceEnabled()) {
              logger.trace(
                  "executing bulk with [{}] actions", bulkRequestBuilder.numberOfActions());
            }

            // if we have no bulk actions we might have processed custom commands, so ack them
            if (ordered || bulkRequestBuilder.numberOfActions() == 0) {
              try {
                if (bulkRequestBuilder.numberOfActions() > 0) {
                  BulkResponse response = bulkRequestBuilder.execute().actionGet();
                  if (response.hasFailures()) {
                    // TODO write to exception queue?
                    logger.warn("failed to execute: " + response.buildFailureMessage());
                  }
                }
              } catch (Exception e) {
                logger.warn("failed to execute bulk", e);
              }
              for (Long deliveryTag : deliveryTags) {
                try {
                  channel.basicAck(deliveryTag, false);
                } catch (Exception e1) {
                  logger.warn("failed to ack [{}]", e1, deliveryTag);
                }
              }
            } else {
              if (bulkRequestBuilder.numberOfActions() > 0) {
                bulkRequestBuilder.execute(
                    new ActionListener<BulkResponse>() {
                      @Override
                      public void onResponse(BulkResponse response) {
                        if (response.hasFailures()) {
                          // TODO write to exception queue?
                          logger.warn("failed to execute: " + response.buildFailureMessage());
                        }
                        for (Long deliveryTag : deliveryTags) {
                          try {
                            channel.basicAck(deliveryTag, false);
                          } catch (Exception e1) {
                            logger.warn("failed to ack [{}]", e1, deliveryTag);
                          }
                        }
                      }

                      @Override
                      public void onFailure(Throwable e) {
                        logger.warn(
                            "failed to execute bulk for delivery tags [{}], not ack'ing",
                            e,
                            deliveryTags);
                      }
                    });
              }
            }
          }
        }
      }
      cleanup(0, "closing river");
    }
 @Override
 protected void executeListener(Channel channel, Message message) throws Throwable {
   super.executeListener(channel, message);
   channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
   if (log.isDebugEnabled()) log.debug("Acknowledging message: " + new String(message.getBody()));
 }
Beispiel #16
0
  /**
   * @param args
   * @throws IOException
   * @throws FileNotFoundException
   * @throws UnsupportedEncodingException
   * @throws InterruptedException
   */
  public static void main(String[] args)
      throws UnsupportedEncodingException, FileNotFoundException, IOException,
          InterruptedException {
    Properties ps = new Properties();
    ps.load(
        new InputStreamReader(
            FileUtil.openPropertiesInputStream("log4j.properties"), FileUtil.fileEncode));
    PropertyConfigurator.configure(ps);

    // 创建线程池
    HSCloudEventHandler job = new HSCloudEventHandler(job_name, max_thread);

    // 从RabbitMQ接收消息并处理
    try {
      // 初始化RabbitMQ连接
      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost(host);
      factory.setUsername(username);
      factory.setPassword(SecurityHelper.DecryptData(password, securityKey));
      Connection connection = factory.newConnection();
      Channel channel = connection.createChannel();
      channel.exchangeDeclare(exchange, "fanout", durable);
      DeclareOk ok = channel.queueDeclare(queue, durable, false, false, null);

      String queueName = ok.getQueue();
      channel.queueBind(queueName, exchange, "");
      channel.basicQos(1); // 消息分发处理
      QueueingConsumer consumer = new QueueingConsumer(channel);
      channel.basicConsume(queueName, false, consumer);
      logger.info(
          "Begin to receive RabbitMQ event: host["
              + host
              + "] exchange["
              + exchange
              + "] queue["
              + queueName
              + "] max-thread["
              + max_thread
              + "]");
      while (true) {
        Date now = new Date();
        if (expirationDate.before(now)) {
          logger.error("证书失效,系统终止服务。");
          System.exit(-1);
        }
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        if (FileUtil.stopProcess()) {
          logger.info("JobServer receive stop process event and will be end.....");
          break;
        }
        String message = new String(delivery.getBody());
        logger.debug(" [" + queue + "] Received '" + message + "'");
        // 处理创建虚拟机的消息,创建虚拟机需要分配ip,多以单独放在一个队列里面处理。
        if (jobServerType.equals("master")) {
          if (message.indexOf("createVM_") != -1) { // 根据消息内容判断消息类型
            try {
              // 对创建vm的消息进行处理,分配ip并填充到消息中
              message = handleMessage(message);
              // 创建线程去向openstack请求创建vm
              job.Handler(message);
            } catch (Exception e) {
              // 如果在分配ip过程中出现异常则捕获,把消息中的result:3,置换为result:4,error_info:错误信息
              logger.error(e.getMessage(), e);
              try {
                // 对消息填充和置换ip分配失败的信息
                message = saveGetIpExceptionLog(message, e.getMessage());
                // 即使ip分配失败仍然创建线程去向openstack请求创建vm
                job.Handler(message);
              } catch (Exception ex) {
                logger.error(ex.getMessage(), e);
              }
              channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
              continue;
            }
          }
          channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else if (jobServerType.equals("slaver")) { // 执行非创建vm的任务
          if (message.indexOf("createVM_") == -1) {
            job.Handler(message);
          }
          channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

        } else if (jobServerType.equals("all")) {
          try {
            message = handleMessage(message);
            job.Handler(message);
          } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
              saveGetIpExceptionLog(message, e.getMessage());
              channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
              continue;
            } catch (Exception ex) {
              logger.error(ex.getMessage(), ex);
            }
          }
          channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
        TimeUnit.MILLISECONDS.sleep(sleepTime);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    // 退出线程池
    job.Shutdown();

    while (!job.IsTerminate()) {
      logger.info("Waiting for JobServer finished!");
    }

    logger.info("JobServer finished!");
    System.exit(0);
  }
  /** {@inheritDoc} */
  @Override
  public SampleResult sample(Entry entry) {
    SampleResult result = new SampleResult();
    result.setSampleLabel(getName());
    result.setSuccessful(false);
    result.setResponseCode("500");

    QueueingConsumer consumer;
    String consumerTag;

    trace("AMQPConsumer.sample()");

    try {
      initChannel();

      consumer = new QueueingConsumer(channel);
      channel.basicQos(1); // TODO: make prefetchCount configurable?
      consumerTag = channel.basicConsume(getQueue(), autoAck(), consumer);
    } catch (IOException ex) {
      log.error("Failed to initialize channel", ex);
      return result;
    }

    result.setSampleLabel(getTitle());
    /*
     * Perform the sampling
     */
    result.sampleStart(); // Start timing
    try {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery(getReceiveTimeoutAsInt());

      if (delivery == null) {
        log.warn("nextDelivery timed out");
        return result;
      }

      /*
       * Set up the sample result details
       */
      result.setSamplerData(new String(delivery.getBody()));

      result.setResponseData("OK", null);
      result.setDataType(SampleResult.TEXT);

      result.setResponseCodeOK();
      result.setResponseMessage("OK");
      result.setSuccessful(true);

      if (!autoAck()) channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

    } catch (ShutdownSignalException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("400");
      result.setResponseMessage(e.toString());
      interrupt();
    } catch (ConsumerCancelledException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("300");
      result.setResponseMessage(e.toString());
      interrupt();
    } catch (InterruptedException e) {
      log.info("interuppted while attempting to consume");
      result.setResponseCode("200");
      result.setResponseMessage(e.toString());
    } catch (IOException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("100");
      result.setResponseMessage(e.toString());
    } finally {
      try {
        channel.basicCancel(consumerTag);
      } catch (IOException e) {
        log.error("Couldn't safely cancel the sample's consumer", e);
      }
    }

    result.sampleEnd(); // End timimg
    trace("AMQPConsumer.sample ended");

    return result;
  }
  @Override
  public PollableSource.Status process() throws EventDeliveryException {
    if (null == _Connection) {
      try {
        if (log.isInfoEnabled())
          log.info(
              this.getName()
                  + " - Opening connection to "
                  + _ConnectionFactory.getHost()
                  + ":"
                  + _ConnectionFactory.getPort());
        _Connection = _ConnectionFactory.newConnection();
        _CounterGroup.incrementAndGet(RabbitMQConstants.COUNTER_NEW_CONNECTION);
        _Channel = null;
      } catch (Exception ex) {
        if (log.isErrorEnabled())
          log.error(this.getName() + " - Exception while establishing connection.", ex);
        resetConnection();
        return Status.BACKOFF;
      }
    }

    if (null == _Channel) {
      try {
        if (log.isInfoEnabled()) log.info(this.getName() + " - creating channel...");
        _Channel = _Connection.createChannel();
        _CounterGroup.incrementAndGet(RabbitMQConstants.COUNTER_NEW_CHANNEL);
        if (log.isInfoEnabled())
          log.info(
              this.getName()
                  + " - Connected to "
                  + _ConnectionFactory.getHost()
                  + ":"
                  + _ConnectionFactory.getPort());

        if (StringUtils.isNotEmpty(_ExchangeName)) {
          try {
            // declare an exchange
            _Channel.exchangeDeclarePassive(_ExchangeName);

            // only grab a default queuename if one is not specified in config
            if (StringUtils.isEmpty(_QueueName)) {
              _QueueName = _Channel.queueDeclare().getQueue();
            }

            // for each topic, bind to the key
            if (null != _Topics) {
              for (String topic : _Topics) {
                _Channel.queueBind(_QueueName, _ExchangeName, topic);
              }
            }
          } catch (Exception ex) {
            if (log.isErrorEnabled())
              log.error(this.getName() + " - Exception while declaring exchange.", ex);
            resetConnection();
            return Status.BACKOFF;
          }
        }
      } catch (Exception ex) {
        if (log.isErrorEnabled())
          log.error(this.getName() + " - Exception while creating channel.", ex);
        resetConnection();
        return Status.BACKOFF;
      }
    }

    GetResponse response;

    try {
      response = _Channel.basicGet(_QueueName, false);
      _CounterGroup.incrementAndGet(RabbitMQConstants.COUNTER_GET);
    } catch (Exception ex) {
      _CounterGroup.incrementAndGet(RabbitMQConstants.COUNTER_EXCEPTION);
      if (log.isErrorEnabled())
        log.error(this.getName() + " - Exception thrown while pulling from queue.", ex);
      resetConnection();
      return Status.BACKOFF;
    }

    if (null == response) {
      _CounterGroup.incrementAndGet(RabbitMQConstants.COUNTER_GET_MISS);
      return Status.BACKOFF;
    }

    try {
      Map<String, String> properties = RabbitMQUtil.getHeaders(response.getProps());

      Event event = new SimpleEvent();
      event.setBody(response.getBody());
      event.setHeaders(properties);

      getChannelProcessor().processEvent(event);
    } catch (Exception ex) {
      if (log.isErrorEnabled())
        log.error(this.getName() + " - Exception thrown while processing event", ex);

      return Status.BACKOFF;
    }

    try {
      _Channel.basicAck(response.getEnvelope().getDeliveryTag(), false);
      _CounterGroup.incrementAndGet(RabbitMQConstants.COUNTER_ACK);
    } catch (Exception ex) {
      _CounterGroup.incrementAndGet(RabbitMQConstants.COUNTER_EXCEPTION);
      if (log.isErrorEnabled())
        log.error(this.getName() + " - Exception thrown while sending ack to queue", ex);
      resetConnection();
      return Status.BACKOFF;
    }

    return Status.READY;
  }