Ejemplo n.º 1
0
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("10.71.49.228");
    factory.setUsername("jinhd");
    factory.setPassword("admin");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer =
        new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
              throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
          }
        };
    channel.basicConsume(queueName, true, consumer);
  }
Ejemplo n.º 2
0
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);

    final Consumer consumer =
        new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
              throws IOException {
            String message = new String(body, "UTF-8");

            System.out.println(" [x] Received '" + message + "'");
            try {
              doWork(message);
            } finally {
              System.out.println(" [x] Done");
              channel.basicAck(envelope.getDeliveryTag(), false);
            }
          }
        };
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
  }
Ejemplo n.º 3
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();
  }
Ejemplo n.º 4
0
 // bug 26552
 public void testServerNamedTransientAutoDeleteQueueAndBindingRecovery()
     throws IOException, InterruptedException, TimeoutException {
   String x = "tmp-fanout";
   Channel ch = connection.createChannel();
   ch.exchangeDelete(x);
   ch.exchangeDeclare(x, "fanout");
   String q = ch.queueDeclare("", false, false, true, null).getQueue();
   final AtomicReference<String> nameBefore = new AtomicReference<String>(q);
   final AtomicReference<String> nameAfter = new AtomicReference<String>();
   final CountDownLatch listenerLatch = new CountDownLatch(1);
   ((AutorecoveringConnection) connection)
       .addQueueRecoveryListener(
           new QueueRecoveryListener() {
             @Override
             public void queueRecovered(String oldName, String newName) {
               nameBefore.set(oldName);
               nameAfter.set(newName);
               listenerLatch.countDown();
             }
           });
   ch.queueBind(nameBefore.get(), x, "");
   restartPrimaryAndWaitForRecovery();
   expectChannelRecovery(ch);
   ch.confirmSelect();
   ch.exchangeDeclare(x, "fanout");
   ch.basicPublish(x, "", null, "msg".getBytes());
   waitForConfirms(ch);
   AMQP.Queue.DeclareOk ok = ch.queueDeclarePassive(nameAfter.get());
   assertEquals(1, ok.getMessageCount());
   ch.queueDelete(nameAfter.get());
   ch.exchangeDelete(x);
 }
 /**
  * If the passed-in queue name is null, creates a server-named temporary exclusive autodelete
  * queue to use; otherwise expects the queue to have already been declared.
  */
 public RpcServer(Channel channel, String queueName) throws IOException {
   _channel = channel;
   if (queueName == null || queueName.equals("")) {
     _queueName = _channel.queueDeclare().getQueue();
   } else {
     _queueName = queueName;
   }
   _consumer = setupConsumer();
 }
Ejemplo n.º 6
0
 private void expectExchangeRecovery(Channel ch, String x)
     throws IOException, InterruptedException, TimeoutException {
   ch.confirmSelect();
   String q = ch.queueDeclare().getQueue();
   final String rk = "routing-key";
   ch.queueBind(q, x, rk);
   ch.basicPublish(x, rk, null, "msg".getBytes());
   waitForConfirms(ch);
   ch.exchangeDeclarePassive(x);
 }
Ejemplo n.º 7
0
    public void testRoutingInvalidRoutes() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        com.rabbitmq.client.Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("transient", false, false, false, null);
        connection.close();

        for (String dest : Arrays.asList("/exchange/missing", "/queue/transient", "/fruit/orange")) {
            routeInvalidSource(dest);
            routeInvalidTarget(dest);
        }
    }
Ejemplo n.º 8
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);
    }
  }
Ejemplo n.º 9
0
 // bug 26552
 public void testClientNamedTransientAutoDeleteQueueAndBindingRecovery()
     throws IOException, InterruptedException, TimeoutException {
   String q = UUID.randomUUID().toString();
   String x = "tmp-fanout";
   Channel ch = connection.createChannel();
   ch.queueDelete(q);
   ch.exchangeDelete(x);
   ch.exchangeDeclare(x, "fanout");
   ch.queueDeclare(q, false, false, true, null);
   ch.queueBind(q, x, "");
   restartPrimaryAndWaitForRecovery();
   expectChannelRecovery(ch);
   ch.confirmSelect();
   ch.queuePurge(q);
   ch.exchangeDeclare(x, "fanout");
   ch.basicPublish(x, "", null, "msg".getBytes());
   waitForConfirms(ch);
   AMQP.Queue.DeclareOk ok = ch.queueDeclare(q, false, false, true, null);
   assertEquals(1, ok.getMessageCount());
   ch.queueDelete(q);
   ch.exchangeDelete(x);
 }
Ejemplo n.º 10
0
 public void testDeclarationOfManyAutoDeleteExchangesWithTransientQueuesThatAreDeleted()
     throws IOException, TimeoutException {
   Channel ch = connection.createChannel();
   assertRecordedExchanges(connection, 0);
   for (int i = 0; i < 5000; i++) {
     String x = UUID.randomUUID().toString();
     ch.exchangeDeclare(x, "fanout", false, true, null);
     String q = ch.queueDeclare().getQueue();
     ch.queueBind(q, x, "doesn't matter");
     ch.queueDelete(q);
   }
   assertRecordedExchanges(connection, 0);
   ch.close();
 }
Ejemplo n.º 11
0
 public void testDeclarationOfManyAutoDeleteQueuesWithTransientConsumer()
     throws IOException, TimeoutException {
   Channel ch = connection.createChannel();
   assertRecordedQueues(connection, 0);
   for (int i = 0; i < 5000; i++) {
     String q = UUID.randomUUID().toString();
     ch.queueDeclare(q, false, false, true, null);
     QueueingConsumer dummy = new QueueingConsumer(ch);
     String tag = ch.basicConsume(q, true, dummy);
     ch.basicCancel(tag);
   }
   assertRecordedQueues(connection, 0);
   ch.close();
 }
Ejemplo n.º 12
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());
    }
  }
Ejemplo n.º 13
0
 public void testConnectionRecoveryWithDisabledTopologyRecovery()
     throws IOException, InterruptedException, TimeoutException {
   AutorecoveringConnection c = newRecoveringConnection(true);
   Channel ch = c.createChannel();
   String q = "java-client.test.recovery.q2";
   ch.queueDeclare(q, false, true, false, null);
   ch.queueDeclarePassive(q);
   assertTrue(c.isOpen());
   try {
     CountDownLatch shutdownLatch = prepareForShutdown(c);
     CountDownLatch recoveryLatch = prepareForRecovery(c);
     Host.closeConnection(c);
     wait(shutdownLatch);
     wait(recoveryLatch);
     assertTrue(c.isOpen());
     ch.queueDeclarePassive(q);
     fail("expected passive declaration to throw");
   } catch (java.io.IOException e) {
     // expected
   } finally {
     c.abort();
   }
 }
    @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");
    }
Ejemplo n.º 15
0
 private AMQP.Queue.DeclareOk declareClientNamedAutoDeleteQueue(Channel ch, String q)
     throws IOException {
   return ch.queueDeclare(q, true, false, true, null);
 }