private void runIt() throws IOException {
    Channel channel = _connection.createChannel();

    String queueName = "test queue";
    channel.queueDeclare(queueName, true, false, false, null);

    String exchangeName = "test completion";
    channel.exchangeDeclare(exchangeName, "fanout", false, false, null);

    String completionQueue = channel.queueDeclare().getQueue();
    channel.queueBind(completionQueue, exchangeName, "");

    LatencyExperimentConsumer callback = new LatencyExperimentConsumer(channel, queueName);
    callback._autoAck = this._autoAck;

    channel.basicConsume(queueName, _autoAck, callback);
    channel.basicConsume(completionQueue, true, "completion", callback);
    callback.report(_writeStats);

    System.out.println("Deleting test queue.");
    channel.queueDelete(queueName);

    System.out.println("Deleting completion queue.");
    channel.queueDelete(completionQueue);

    System.out.println("Closing the channel.");
    channel.close();

    System.out.println("Closing the connection.");
    _connection.close();

    System.out.println("Leaving ConsumerMain.run().");
  }
 protected String createDynamicQueue(
     String exchange, String routingKey, boolean isPoisonQueueEnabled) throws IOException {
   String queue = channel.queueDeclare().getQueue();
   channel.queueBind(queue, exchange, routingKey);
   if (isPoisonQueueEnabled) {
     String poisonQueue = POISON + "." + queue;
     Map<String, Object> settings = new HashMap<String, Object>();
     channel.queueDeclare(poisonQueue, true, true, true, settings);
     channel.queueBind(poisonQueue, exchange, routingKey + "." + queue + POISON);
   }
   return queue;
 }
  public void getFromServer() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://*****:*****@10.184.186.243:5672/%2F");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    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 orderString = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + orderString + "'");
            OrderSerialize os = new OrderSerialize();
            Orders order = os.StringToOrder(orderString);
            System.out.println("Now we get the order:" + order + "now save it into db");
            System.out.println("Now call test beans to check what benas we have in spring");
            ;
            // testbeans();
            if (null == om) {
              System.out.println(
                  "The injected Ordersmanager is null, exception shows, the order has not been saved into DB ");
              return;
            } else {
              om.saveOrders(order);
            }
          }
        };
    channel.basicConsume(QUEUE_NAME, true, consumer);
  }
  @Override
  public boolean endSubscribtionToChannel(String exchangeName) {
    Channel channel = subscribedChannels.get(exchangeName);
    if (channel != null) {
      try {
        String queueName = channel.queueDeclare().getQueue();
        channel.queueUnbind(queueName, exchangeName, "");
        //				channel.basicConsume(queueName, arg1)

        //				channel.close(0,exchangeName);
        subscribedChannels.remove(exchangeName);
        channel = null;
        Log.i(
            LOGTAG,
            "subscribed to "
                + subscribedChannels.size()
                + " Channels"
                + "\n"
                + "ended subscribtion to : "
                + exchangeName);
        return true;
      } catch (AlreadyClosedException e) {
        Log.e(LOGTAG, "endSubcribtionToChannel: " + e.toString());
        subscribedChannels.remove(exchangeName);
      } catch (IOException e) {
        Log.e(LOGTAG, "endSubcribtionToChannel: " + e.toString());
      } catch (ShutdownSignalException e) {
        Log.e(LOGTAG, "endSubcribtionToChannel: " + e.toString());
      }
    }
    return false;
  }
Beispiel #5
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 #6
0
  @Override
  public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    try {
      // setup connection
      ConnectionFactory factory = new ConnectionFactory();
      if (amqpUri == null) {
        factory.setHost("localhost");
      } else {
        factory.setUri(amqpUri);
      }
      Connection connection = factory.newConnection();
      LOG.info(" [RabbitWriter] Connected to Rabbit");

      // setup channels
      sendChannel = connection.createChannel();
      Map<String, Object> args = map();
      args.put("x-max-length", 1000);
      sendChannel.queueDeclare(queue, DURABLE, false, false, args);

    } catch (Exception e) {
      throw new ResourceInitializationException(e);
    }
  }
Beispiel #7
0
  public static void main(String[] args) throws IOException, TimeoutException {
    // Setting up is the same as the sender;
    //		we open a connection and a channel, and declare the queue from which we're going to consume.
    //		Note this matches up with the queue that send publishes to.
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST_ADDRESS);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    //		Note that we declare the queue here, as well.
    //		Because we might start the receiver before the sender,
    //		we want to make sure the queue exists before we try to consume messages from it.
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println("[*] waiting for message .To exit press CTRL+C");
    //		We're about to tell the server to deliver us the messages from the queue.
    //		Since it will push us messages asynchronously, we provide a callback in the form of an
    // object that
    //		will buffer the messages until we're ready to use them. That is what a DefaultConsumer
    // subclass does.
    Consumer consumer =
        new DefaultConsumer(channel) {

          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
              throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
          }
        };
    channel.basicConsume(QUEUE_NAME, true, consumer);
  }
Beispiel #8
0
  public static void main(String[] argv) throws java.io.IOException, TimeoutException {

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

    /*
     * The durability options let the tasks survive even if RabbitMQ is
     * restarted
     */
    boolean durable = true;
    channel.queueDeclare(TASK_QUEUE_NAME, durable, false, false, null);

    String message = getMessage(argv);

    /*
     * publish 設成 persistent 的用處是為了防止RabbitMQ server gg 時忘記message 的內容
     */
    channel.basicPublish(
        "", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
  }
Beispiel #9
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();
  }
 // 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);
 }
Beispiel #11
0
  public static void main(String[] args) throws IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost("localhost");

    Connection connection = factory.newConnection();

    Channel channel = connection.createChannel();

    channel.exchangeDeclare(Work.EXCHANGE_NAME, "fanout");

    String randomQueName = channel.queueDeclare().getQueue();

    channel.queueBind(randomQueName, Work.EXCHANGE_NAME, "");

    // channel.queueDeclare(QUEUE_NAME, true, false, false, null);

    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 + "'" + Thread.currentThread().getName());
          }
        };

    channel.basicConsume(randomQueName, true, consumer);
  }
  @Override
  public String amqpRegister(User user) throws Exception {

    try {
      Channel rabbitMqChannel = rabbitMqConnection.createChannel();

      // create or get user queue
      AMQP.Queue.DeclareOk queue =
          rabbitMqChannel.queueDeclare(
              "USER_".concat(String.valueOf(user.hashCode())),
              true, // durable
              false, // exclusive
              false, // auto delete
              null // no arguments
              );

      Map<String, Object> bindParams = new HashMap<>();
      bindParams.put(ARGUMENT_TO_ID, user.getId());
      rabbitMqChannel.queueBind(queue.getQueue(), amqpExchange, "", bindParams);
      channelListener.registerChannel(rabbitMqChannel, queue.getQueue(), false);

      // add user channel to active channels
      USER_CHANNEL.put(user, rabbitMqChannel);
      return queue.getQueue();

    } catch (Exception e) {
      logger.info("### Couldn't create user queue .. -> {" + e.getMessage() + "}");
      throw e;
    }
  }
  public static void main(String[] arg) throws IOException, InterruptedException {

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

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

    if (arg.length < 1) {
      System.err.println("Usage: ReceiveLogsDirect [info] [warning] [error]");
      System.exit(1);
    }

    for (String severity : arg) {
      channel.queueBind(queueName, EXCHANGE_NAME, severity);
    }

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

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);

    while (true) {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery();
      String message = new String(delivery.getBody());
      String routingKey = delivery.getEnvelope().getRoutingKey();

      System.out.println(" [x] Received '" + routingKey + "':'" + message + "'");
    }
  }
  /** Test that an AMQP client can connect to and use the broker. */
  @Test(groups = {"Integration", "WIP"})
  public void testClientConnection() throws Exception {
    rabbit = app.createAndManageChild(EntitySpec.create(RabbitBroker.class));
    rabbit.start(ImmutableList.of(testLocation));
    EntityTestUtils.assertAttributeEqualsEventually(rabbit, Startable.SERVICE_UP, true);

    byte[] content = "MessageBody".getBytes(Charsets.UTF_8);
    String queue = "queueName";
    Channel producer = null;
    Channel consumer = null;
    try {
      producer = getAmqpChannel(rabbit);
      consumer = getAmqpChannel(rabbit);

      producer.queueDeclare(queue, true, false, false, ImmutableMap.<String, Object>of());
      producer.queueBind(queue, AmqpExchange.DIRECT, queue);
      producer.basicPublish(AmqpExchange.DIRECT, queue, null, content);

      QueueingConsumer queueConsumer = new QueueingConsumer(consumer);
      consumer.basicConsume(queue, true, queueConsumer);

      QueueingConsumer.Delivery delivery =
          queueConsumer.nextDelivery(60 * 1000l); // one minute timeout
      assertEquals(delivery.getBody(), content);
    } finally {
      closeSafely(producer, 10 * 1000);
      closeSafely(consumer, 10 * 1000);
    }
  }
Beispiel #15
0
  public static void main(String[] args) throws IOException, InterruptedException {
    Random random = new Random();
    int i = random.nextInt(10);
    String clientName = "client-" + i;

    Channel channel = RabbitUtil.getChannel();
    // 申明交换器
    channel.exchangeDeclare(C.FANOUT_EXCHANGE, "fanout");

    // 匿名队列
    String queueName = channel.queueDeclare().getQueue();
    System.err.println("queueName:" + queueName);

    // 绑定队列到交换器
    AMQP.Queue.BindOk bindOk = channel.queueBind(queueName, C.FANOUT_EXCHANGE, "");
    System.err.println("bindOk:" + bindOk);

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

    QueueingConsumer consumer = new QueueingConsumer(channel);

    channel.basicConsume(queueName, true, consumer);

    while (true) {

      QueueingConsumer.Delivery delivery = consumer.nextDelivery();
      String message = new String(delivery.getBody());

      System.out.println(clientName + " Received :" + message + "");
      Thread.sleep(1000);
    }
  }
Beispiel #16
0
  public void start() throws IOException {
    String queueName = "chat" + user + "/" + chan.getChannelNumber();

    final boolean durable = true;
    final boolean exclusive = true;
    final boolean autodelete = true;
    chan.queueDeclare(queueName, durable, exclusive, autodelete, null);
    chan.queueBind(queueName, "amq.fanout", "chat");

    chan.basicConsume(
        queueName,
        new DefaultConsumer(chan) {
          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
              throws IOException {
            String message = new String(body, "UTF-8");
            try {
              connectionMetaInfo.socket.send(message);

              chan.basicAck(envelope.getDeliveryTag(), false);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        });
  }
 public boolean notice() {
   try {
     String searchServices = VrsMqConfig.VRS_MQ_SEARCH_SERVICE;
     for (String service : searchServices.split(",")) {
       String exchange = "";
       String routingKey = VrsMqConfig.VRS_MQ_ROUTINGKEY + "_search_" + service;
       cfconn.setUri(VrsMqConfig.VRS_MQ_HOSTNAME);
       cfconn.setPort(VrsMqConfig.VRS_MQ_PORT);
       cfconn.setUsername(VrsMqConfig.VRS_MQ_USERNAME);
       cfconn.setPassword(VrsMqConfig.VRS_MQ_PASSWORD);
       Connection conn = cfconn.newConnection();
       Channel ch = conn.createChannel();
       if (exchange.equals("")) {
         ch.queueDeclare(routingKey, false, false, false, null);
       }
       String message = "sync";
       logger.info("=========notice=========:" + message);
       ch.basicPublish(exchange, routingKey, null, message.getBytes());
       ch.close();
       conn.close();
     }
     return true;
   } catch (Exception e) {
     System.err.println("Main thread caught exception: " + e);
     e.printStackTrace();
     return false;
   }
 }
Beispiel #18
0
  public static void main(String[] argv) throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = "Kender du hende der Arne";
    channel.queueDeclare(queueName, false, false, false, null);

    channel.queueBind(queueName, EXCHANGE_NAME, "");
    String messageOut =
        "{\"ssn\":1605789787,\"creditScore\":699,\"loanAmount\":10.0,\"loanDuration\":360}";
    BasicProperties.Builder props = new BasicProperties().builder();
    props.replyTo("");
    BasicProperties bp = props.build();
    channel.basicPublish(EXCHANGE_NAME, "", bp, messageOut.getBytes());
    System.out.println(" [x] Sent by JSONtester: '" + messageOut + "'");

    channel.close();
    connection.close();
  }
Beispiel #19
0
  /**
   * 从指定队列接收消息,然后通过观察者对象处理
   *
   * @param queueName
   * @param observer
   * @throws Exception
   */
  public void receive(String queueName, IObserver observer) throws Exception {
    try {
      this.init();

      // 指定队列
      channel.queueDeclare(queueName, true, false, false, null);

      // 绑定队列到指定的交换机
      // channel.queueBind(queueName, mqExchangeName, queueName);
      // log.info("Bind queue {} to {} success! ", queueName, mqExchangeName);

      QueueingConsumer consumer = new QueueingConsumer(channel);
      channel.basicConsume(queueName, true, consumer);

      while (true) {
        // 阻塞,直到接收到一条消息
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        log.info("Received a message: " + message);

        observer.update(message);
      }

    } finally {
      this.destory();
    }
  }
Beispiel #20
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);
  }
Beispiel #21
0
  public String recvFromMessagequeue() {

    RabbitmqClientConf client = new RabbitmqClientConf();
    Channel channel = client.getChannel();

    try {
      channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    } catch (IOException e) {
      e.printStackTrace();
    }

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

    QueueingConsumer consumer = new QueueingConsumer(channel);

    try {
      channel.basicConsume(QUEUE_NAME, true, consumer);
    } catch (IOException e) {
      e.printStackTrace();
    }

    System.out.println("ready to receive");

    QueueingConsumer.Delivery delivery = null;
    try {
      delivery = consumer.nextDelivery();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    String message = new String(delivery.getBody());
    System.out.println("[x] Received'" + message + "'");

    return message;
  }
  public static void main(String[] argv)
      throws java.io.IOException, java.lang.InterruptedException, TimeoutException {
    // 创建连接和频道
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    // 声明direct类型转发器
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    String queueName = channel.queueDeclare().getQueue();
    String severity = getSeverity();
    // 指定binding_key
    channel.queueBind(queueName, EXCHANGE_NAME, severity);
    System.out.println(" [*] Waiting for " + severity + " logs. To exit press CTRL+C");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);

    while (true) {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery();
      String message = new String(delivery.getBody());

      System.out.println(" [x] Received '" + message + "'");
    }
  }
  @Override
  public boolean subscribeToChannel(String exchangeName, String type) {
    if (!connected) {
      return false;
    }
    try {
      // we create a new channel
      Channel channel = connection.createChannel();
      channel.exchangeDeclare(exchangeName, type);
      String queueName = channel.queueDeclare().getQueue();
      channel.queueBind(queueName, exchangeName, "");

      // we define what happens if we recieve a new Message
      channel.basicConsume(queueName, new RabbitMQConsumer(channel, service));
      subscribedChannels.putIfAbsent(exchangeName, channel);
      Log.i(
          LOGTAG,
          "subscribed to "
              + subscribedChannels.size()
              + " Channels"
              + "\n"
              + "started subscribtion to : "
              + exchangeName);
      return true;
    } catch (Exception e) {
      Log.e(LOGTAG, "Connection Problem at subscribeToChannel(): " + e.toString());
    }
    return false;
  }
  @Test
  public void testBasicConnectivity() {
    String sentMsg = "sent";
    String recvdMsg = "received";
    try {
      channel.queueDeclare(basicTestQueue, false, false, false, null);
      sentMsg = "testBasicConnectivity";
      channel.basicPublish("", basicTestQueue, null, sentMsg.getBytes());

      QueueingConsumer consumer = new QueueingConsumer(channel);
      channel.basicConsume(basicTestQueue, true, consumer);
      QueueingConsumer.Delivery delivery = consumer.nextDelivery(1500);
      if (delivery != null) {
        recvdMsg = new String(delivery.getBody());
      }

    } catch (Exception ex) {
      fail("Connectivity error to MQ while running Test" + ex);
    } finally {
      try {
        channel.close();
        connection.close();
      } catch (Exception ex) {
        fail("Connectivity error to MQ while running Test" + ex);
      }
    }
    assertEquals(sentMsg, recvdMsg);
  }
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {
      channel.exchangeDeclare(EXCHANGE_NAME, "direct");
      String queueName = channel.queueDeclare().getQueue();

      String severity = "warning";
      channel.queueBind(queueName, EXCHANGE_NAME, severity);

      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 '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
          };
      channel.basicConsume(queueName, true, consumer);
      while (true) {}
    } finally {
      channel.close();
      connection.close();
    }
  }
Beispiel #26
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);
  }
Beispiel #27
0
 public void connect() {
   ConnectionFactory factory = new ConnectionFactory();
   try {
     factory.setUsername("guest");
     factory.setPassword("guest");
     factory.setVirtualHost("/");
     factory.setHost("localhost");
     factory.setPort(5672);
     conn = factory.newConnection();
     channel = conn.createChannel();
     String exchangeName = "exchange." + Math.abs((new Random()).nextInt());
     String queueName = "queue";
     String routingKey = "route";
     boolean durable = true;
     channel.exchangeDeclare(exchangeName, "topic", durable);
     channel.queueDeclare(queueName, durable, false, false, null);
     channel.queueBind(queueName, exchangeName, routingKey);
     consumer = new QueueingConsumer(channel);
     channel.basicConsume(queueName, false, consumer);
   } catch (IOException e) {
     e.printStackTrace();
   } catch (TimeoutException e) {
     e.printStackTrace();
   }
 }
  protected Map<String, Channel> initChannel(
      Connection connection, int assignedNum, String queueName) throws IOException {
    Channel consumerChannel = connection.createChannel();
    Channel publisherChannel = connection.createChannel();

    Map<String, Channel> result = new HashMap<String, Channel>();

    if (consumerChannel != null && !consumerChannel.isOpen()) {

      consumerChannel = connection.createChannel();
    }
    if (publisherChannel != null && !publisherChannel.isOpen()) {
      publisherChannel = connection.createChannel();
    }

    DecimalFormat formatter = new DecimalFormat("#00.###");

    String queueRoutingKey = CONSUMER_ROUTING_KEY + formatter.format(assignedNum);

    consumerChannel.queueDeclare(queueName, false, false, true, null);
    consumerChannel.exchangeDeclare(CONSUMER_EXCHANGE_NAME, CONSUMER_EXCHANGE_TYPE, false);
    consumerChannel.queueBind(queueName, CONSUMER_EXCHANGE_NAME, queueRoutingKey);
    consumerChannel.basicQos(1);
    publisherChannel.exchangeDeclare(PUBLISHER_EXCHANGE_NAME, PUBLISHER_EXCHANGE_TYPE, false);
    result.put("consumer", consumerChannel);
    result.put("publisher", publisherChannel);
    return result;
  }
Beispiel #29
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);
    }
  }
  @Test
  public void testStreamingEvent() {
    // Instantiate the resource
    ResourceImpl resourceImpl = new ResourceImpl(restItem);

    try {
      channel.queueDeclare(intTestQueue, false, false, false, null);
    } catch (Exception ex) {
      fail("Connectivity error to MQ while running Test" + ex);
      try {
        channel.close();
        connection.close();
      } catch (Exception otherEx) {
        // We couldn't close a connection that's already closed or
        // hasn't been open...
      }
    }

    // Here we build the queue ResourceImpl is going to connect to and we
    // will later publish to
    try {
      resourceImpl.startStreaming(createListeners());
    } catch (Exception ex) {
      fail("Error while starting streaming service: " + ex);
    }

    // Have a rest to let all the services start up properly
    try {
      Thread.sleep(5000);
      channel.basicPublish("", intTestQueue, null, mqMessage.getBytes());
    } catch (Exception ex) {
      fail("Cannot publish to MQ on test environment" + ex);
    }

    // A little rest to let the publication go through
    try {
      Thread.sleep(2000);
    } catch (Exception ex) {
    }

    // 1st test: did we get a callback on ConnectedEvent (Connected to MQ) ?
    assertTrue(connectedEventCalled);

    // 2nd test: The stream received event was triggered
    assertTrue(streamEventCalled);

    // 3rd test: And the message received was the same as posted on the
    // Queue
    assertEquals(mqMessage, recvdFromMq);

    resourceImpl.mqDisconnectEvent();
    // Have a rest to let all the services shut down up properly
    try {
      Thread.sleep(2000);
      channel.queuePurge(intTestQueue);
    } catch (Exception ex) {
      // Bit of housekeeping
    }
  }