Пример #1
1
  /** @param args [0] RabbitmqHost */
  public static void main(String[] args) {
    System.out.println(Constants.HEADER);
    String RabbitmqHost = "localhost";
    if (args.length > 0) RabbitmqHost = args[0];

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(RabbitmqHost);

    try {
      Connection connection = factory.newConnection();
      System.out.println("Connected: " + RabbitmqHost);
      Channel channel = connection.createChannel();
      channel.exchangeDeclare(Constants.exchange, "direct", false);
      Stats stats = new Stats();
      JSONWriter rabbitmqJson = new JSONWriter();
      int msgCount = 0;
      for (; ; ) {
        stats.Update();
        String statMsg = rabbitmqJson.write(stats);
        System.out.println(stats.toString());
        channel.basicPublish(Constants.exchange, Constants.routingKey, null, statMsg.getBytes());
        ++msgCount;
        if (System.in.available() > 0) break;
        Thread.sleep(1000);
      }
      channel.close();
      System.out.println("Done: " + msgCount + " messages sent");
      connection.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #2
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);
  }
 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;
   }
 }
  @Test
  public void testCloseInvalidConnection() throws Exception {

    com.rabbitmq.client.ConnectionFactory mockConnectionFactory =
        mock(com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection1 = mock(com.rabbitmq.client.Connection.class);
    com.rabbitmq.client.Connection mockConnection2 = mock(com.rabbitmq.client.Connection.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null))
        .thenReturn(mockConnection1)
        .thenReturn(mockConnection2);
    // simulate a dead connection
    when(mockConnection1.isOpen()).thenReturn(false);

    AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory);

    Connection connection = connectionFactory.createConnection();
    // the dead connection should be discarded
    connection.createChannel(false);
    verify(mockConnectionFactory, times(2)).newConnection((ExecutorService) null);
    verify(mockConnection2, times(1)).createChannel();

    connectionFactory.destroy();
    verify(mockConnection2, times(1)).close();
  }
Пример #5
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);
  }
Пример #6
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);
  }
Пример #7
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);
    }
  }
Пример #8
0
  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;
  }
Пример #9
0
  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 + "'");
    }
  }
Пример #10
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);
    }
  }
Пример #11
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);
    }
  }
  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().");
  }
Пример #13
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);
  }
Пример #14
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();
  }
Пример #15
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();
  }
  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();
    }
  }
  public static void main(String[] argv) throws java.io.IOException {

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

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    System.out.println(
        "Type message to send to logs.\n"
            + "Format ${severity}:${message}\n"
            + "    or ${message} (uses default severity 'error')\n"
            + "Type an empty message to exit this process.");
    try {
      while (true) {
        Message message = getMessage();
        if (message == null) {
          break;
        }
        channel.basicPublish(EXCHANGE_NAME, message.severity, null, message.msg.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
      }
    } finally {
      channel.close();
      connection.close();
    }
  }
  /** - */
  @Test
  public void test() throws Exception {

    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    when(mockChannel.isOpen()).thenReturn(true);

    Message msg =
        this.messageConverter.toMessage(
            createFieldChangedEvent(
                "/asset/assetMeter/crank-frame-dischargepressure", //$NON-NLS-1$
                "/asset/assetMeter/crank-frame-dischargepressure", //$NON-NLS-1$
                "/asset/compressor-2015", //$NON-NLS-1$
                StringUtil.parseDate("2012-09-11T07:16:13"), // $NON-NLS-1$
                null,
                null),
            null);

    final RabbitTemplate fieldChangedEventTemplate =
        new RabbitTemplate(new CachingConnectionFactory(mockConnectionFactory));
    fieldChangedEventTemplate.convertAndSend("fieldchangedeventMainQ", msg); // $NON-NLS-1$
  }
  @Test
  public void testPublisherConfirmNotReceived() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    doReturn(new PublisherCallbackChannelImpl(mockChannel)).when(mockConnection).createChannel();

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setPublisherConfirms(true);
    final RabbitTemplate template = new RabbitTemplate(ccf);

    final AtomicBoolean confirmed = new AtomicBoolean();
    template.setConfirmCallback(
        new ConfirmCallback() {

          @Override
          public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            confirmed.set(true);
          }
        });
    template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc"));
    Thread.sleep(5);
    Collection<CorrelationData> unconfirmed = template.getUnconfirmed(-1);
    assertEquals(1, unconfirmed.size());
    assertEquals("abc", unconfirmed.iterator().next().getId());
    assertFalse(confirmed.get());
  }
  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);
  }
Пример #21
0
  public void doCounsumer() throws IOException, TimeoutException {
    factory.setHost("localhost");
    factory.setVirtualHost("epush");
    factory.setUsername("epush");
    factory.setPassword("epush");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    Consumer consumer =
        new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(
              String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
              throws IOException {
            try {
              OtpInputStream InputStream = new OtpInputStream(body);
              OtpErlangTuple login = (OtpErlangTuple) OtpErlangTuple.decode(InputStream);

              LoginEvent loginEvent = new LoginEvent(login);

              System.out.println(loginEvent);

              // mapper.writeValueAsString(loginEvent);

            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };

    channel.basicConsume("epush-login-queue", consumer);
  }
  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 + "'");
    }
  }
Пример #23
0
  public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {
      ConnectionFactory factory = new ConnectionFactory();
      factory.setHost("localhost");

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

      channel.exchangeDeclare(EXCHANGE_NAME, "topic");

      String routingKey = getRouting(argv);
      String message = getMessage(argv);

      channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
      System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (Exception ignore) {
        }
      }
    }
  }
  @Test
  public void channelMaxLowerThanServerMinimum() throws Exception {
    int n = 64;
    ConnectionFactory cf = TestUtils.connectionFactory();
    cf.setRequestedChannelMax(n);

    Connection conn = cf.newConnection();
    assertEquals(n, conn.getChannelMax());
  }
 private Channel getAmqpChannel(RabbitBroker rabbit) throws Exception {
   String uri = rabbit.getAttribute(MessageBroker.BROKER_URL);
   log.warn("connecting to rabbit {}", uri);
   ConnectionFactory factory = new ConnectionFactory();
   factory.setUri(uri);
   Connection conn = factory.newConnection();
   Channel channel = conn.createChannel();
   return channel;
 }
Пример #26
0
  public void stop() throws IOException {
    if (channel != null && channel.isOpen()) {
      channel.close();
    }

    if (connection != null && connection.isOpen()) {
      connection.close();
    }
  }
  // AMQP-506 ConcurrentModificationException
  @Test
  public void testPublisherConfirmGetUnconfirmedConcurrency() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);
    when(mockChannel.isOpen()).thenReturn(true);
    final AtomicLong seq = new AtomicLong();
    doAnswer(
            new Answer<Long>() {

              @Override
              public Long answer(InvocationOnMock invocation) throws Throwable {
                return seq.incrementAndGet();
              }
            })
        .when(mockChannel)
        .getNextPublishSeqNo();

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    doReturn(mockChannel).when(mockConnection).createChannel();

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setPublisherConfirms(true);
    final RabbitTemplate template = new RabbitTemplate(ccf);

    final AtomicBoolean confirmed = new AtomicBoolean();
    template.setConfirmCallback(
        new ConfirmCallback() {

          @Override
          public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            confirmed.set(true);
          }
        });
    ExecutorService exec = Executors.newSingleThreadExecutor();
    final AtomicBoolean sentAll = new AtomicBoolean();
    exec.execute(
        new Runnable() {

          @Override
          public void run() {
            for (int i = 0; i < 10000; i++) {
              template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc"));
            }
            sentAll.set(true);
          }
        });
    Collection<CorrelationData> unconfirmed = template.getUnconfirmed(-1);
    long t1 = System.currentTimeMillis();
    while (!sentAll.get() && System.currentTimeMillis() < t1 + 20000) {
      unconfirmed = template.getUnconfirmed(-1);
    }
    assertTrue(sentAll.get());
    assertFalse(confirmed.get());
  }
  @Test
  public void testReplyToOneDeepCustomCorrelationKey() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    final RabbitTemplate template =
        new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    template.setCorrelationKey(CORRELATION_HEADER);
    Queue replyQueue = new Queue("new.replyTo");
    template.setReplyQueue(replyQueue);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setReplyTo("replyTo1");
    messageProperties.setCorrelationId("saveThis".getBytes());
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicReference<String> replyTo = new AtomicReference<String>();
    final AtomicReference<String> correlationId = new AtomicReference<String>();
    doAnswer(
            new Answer<Object>() {
              public Object answer(InvocationOnMock invocation) throws Throwable {
                BasicProperties basicProps = (BasicProperties) invocation.getArguments()[4];
                replyTo.set(basicProps.getReplyTo());
                correlationId.set((String) basicProps.getHeaders().get(CORRELATION_HEADER));

                MessageProperties springProps =
                    new DefaultMessagePropertiesConverter()
                        .toMessageProperties(basicProps, null, "UTF-8");
                Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
                template.onMessage(replyMessage);
                return null;
              }
            })
        .when(mockChannel)
        .basicPublish(
            Mockito.any(String.class),
            Mockito.any(String.class),
            Mockito.anyBoolean(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertNotNull(replyTo.get());
    assertEquals("new.replyTo", replyTo.get());
    assertNotNull(correlationId.get());
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
    assertTrue(!"saveThis".equals(correlationId.get()));
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
  }
Пример #29
0
 @Override
 protected void closeImpl() throws IOException {
   // ! We are going to assume that closing an already closed
   //  connection is considered success.
   if (connection != null && connection.isOpen()) {
     try {
       connection.close(factory.getConnectionTimeout());
     } catch (AlreadyClosedException ignored) {
     }
   }
 }
Пример #30
0
 @Bean
 QueueingConsumer queueingConsumer() throws IOException {
   ConnectionFactory factory = new ConnectionFactory();
   factory.setHost(messageQueueHostname);
   Connection connection = factory.newConnection();
   Channel channel = connection.createChannel();
   channel.queueDeclare(Constants.ANSWERSHEET_DATA_QUEUE, true, false, false, null);
   QueueingConsumer consumer = new QueueingConsumer(channel);
   channel.basicConsume(Constants.ANSWERSHEET_DATA_QUEUE, true, consumer);
   return consumer;
 }