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;
  }
Esempio n. 2
0
  public void testChannelRecovery() throws IOException, InterruptedException {
    Channel ch1 = connection.createChannel();
    Channel ch2 = connection.createChannel();

    assertTrue(ch1.isOpen());
    assertTrue(ch2.isOpen());
    closeAndWaitForRecovery();
    expectChannelRecovery(ch1);
    expectChannelRecovery(ch2);
  }
  /** - */
  @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$
  }
Esempio n. 4
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());
  }
Esempio n. 6
0
 @Override
 protected void stopImpl() throws IOException {
   // ! As with closing the connection, closing an already
   //  closed channel is considered success.
   if (channel != null && channel.isOpen()) {
     try {
       channel.close();
     } catch (AlreadyClosedException ignored) {
     }
   }
 }
  public void start() throws IOException {
    if (channel == null || !channel.isOpen()) {
      channel = config.createChannel();
      channel.addShutdownListener(this);
      channel.basicQos(getPrefetchCount());

      config.declareBrokerConfiguration(channel);

      consumer = new QueueSubscriber<BasicConsumer<C, T>>(channel, this);
      channel.basicConsume(queueName, false, consumer);
    }
  }
 public void close() {
   try {
     if (channel != null && channel.isOpen()) {
       if (consumerTag != null) channel.basicCancel(consumerTag);
       channel.close();
     }
   } catch (Exception e) {
     logger.debug("error closing channel and/or cancelling consumer", e);
   }
   try {
     logger.info("closing connection to rabbitmq: " + connection);
     connection.close();
   } catch (Exception e) {
     logger.debug("error closing connection", e);
   }
   consumer = null;
   consumerTag = null;
   channel = null;
   connection = null;
 }
  @Test
  public void testPublisherConfirmNotReceivedMultiThreads() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);
    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);
    when(mockChannel1.getNextPublishSeqNo()).thenReturn(1L, 2L, 3L, 4L);
    when(mockChannel2.getNextPublishSeqNo()).thenReturn(1L, 2L, 3L, 4L);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    PublisherCallbackChannelImpl channel1 = new PublisherCallbackChannelImpl(mockChannel1);
    PublisherCallbackChannelImpl channel2 = new PublisherCallbackChannelImpl(mockChannel2);
    when(mockConnection.createChannel()).thenReturn(channel1).thenReturn(channel2);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setPublisherConfirms(true);
    ccf.setChannelCacheSize(3);
    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);
          }
        });

    // Hold up the first thread so we get two channels
    final CountDownLatch threadLatch = new CountDownLatch(1);
    final CountDownLatch threadSentLatch = new CountDownLatch(1);
    // Thread 1
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(
        new Runnable() {

          @Override
          public void run() {
            template.execute(
                new ChannelCallback<Object>() {
                  @Override
                  public Object doInRabbit(Channel channel) throws Exception {
                    try {
                      threadLatch.await(10, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                      Thread.currentThread().interrupt();
                    }
                    template.doSend(
                        channel,
                        "",
                        ROUTE,
                        new SimpleMessageConverter().toMessage("message", new MessageProperties()),
                        false,
                        new CorrelationData("def"));
                    threadSentLatch.countDown();
                    return null;
                  }
                });
          }
        });

    // Thread 2
    template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); // channel y
    threadLatch.countDown();
    assertTrue(threadSentLatch.await(5, TimeUnit.SECONDS));
    Collection<CorrelationData> unconfirmed = template.getUnconfirmed(-1);
    assertEquals(2, unconfirmed.size());
    Set<String> ids = new HashSet<String>();
    Iterator<CorrelationData> iterator = unconfirmed.iterator();
    ids.add(iterator.next().getId());
    ids.add(iterator.next().getId());
    assertTrue(ids.remove("abc"));
    assertTrue(ids.remove("def"));
    assertFalse(confirmed.get());
    DirectFieldAccessor dfa = new DirectFieldAccessor(template);
    Map<?, ?> pendingConfirms = (Map<?, ?>) dfa.getPropertyValue("pendingConfirms");
    assertThat(pendingConfirms.size(), greaterThan(0)); // might use 2 or only 1 channel
    exec.shutdown();
    assertTrue(exec.awaitTermination(10, TimeUnit.SECONDS));
    ccf.destroy();
    assertEquals(0, pendingConfirms.size());
  }
  /** Verifies that an up-stack RabbitTemplate uses the listener's channel (MessageListener). */
  @SuppressWarnings("unchecked")
  @Test
  public void testMessageListener() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    final Channel onlyChannel = mock(Channel.class);
    when(onlyChannel.isOpen()).thenReturn(true);

    final CachingConnectionFactory cachingConnectionFactory =
        new CachingConnectionFactory(mockConnectionFactory);

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

    final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();

    doAnswer(
            new Answer<Channel>() {
              boolean done;

              @Override
              public Channel answer(InvocationOnMock invocation) throws Throwable {
                if (!done) {
                  done = true;
                  return onlyChannel;
                }
                tooManyChannels.set(new Exception("More than one channel requested"));
                Channel channel = mock(Channel.class);
                when(channel.isOpen()).thenReturn(true);
                return channel;
              }
            })
        .when(mockConnection)
        .createChannel();

    final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();

    doAnswer(
            new Answer<String>() {

              @Override
              public String answer(InvocationOnMock invocation) throws Throwable {
                consumer.set((Consumer) invocation.getArguments()[6]);
                return null;
              }
            })
        .when(onlyChannel)
        .basicConsume(
            anyString(),
            anyBoolean(),
            anyString(),
            anyBoolean(),
            anyBoolean(),
            anyMap(),
            any(Consumer.class));

    final CountDownLatch commitLatch = new CountDownLatch(1);
    doAnswer(
            new Answer<String>() {

              @Override
              public String answer(InvocationOnMock invocation) throws Throwable {
                commitLatch.countDown();
                return null;
              }
            })
        .when(onlyChannel)
        .txCommit();

    final CountDownLatch latch = new CountDownLatch(1);
    SimpleMessageListenerContainer container =
        new SimpleMessageListenerContainer(cachingConnectionFactory);
    container.setMessageListener(
        new MessageListener() {
          @Override
          public void onMessage(Message message) {
            RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
            rabbitTemplate.setChannelTransacted(true);
            // should use same channel as container
            rabbitTemplate.convertAndSend("foo", "bar", "baz");
            latch.countDown();
          }
        });
    container.setQueueNames("queue");
    container.setChannelTransacted(true);
    container.setShutdownTimeout(100);
    container.afterPropertiesSet();
    container.start();

    consumer
        .get()
        .handleDelivery(
            "qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] {0});

    assertTrue(latch.await(10, TimeUnit.SECONDS));

    Exception e = tooManyChannels.get();
    if (e != null) {
      throw e;
    }

    verify(mockConnection, Mockito.times(1)).createChannel();
    assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
    verify(onlyChannel).txCommit();
    verify(onlyChannel)
        .basicPublish(
            Mockito.anyString(),
            Mockito.anyString(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));

    // verify close() was never called on the channel
    DirectFieldAccessor dfa = new DirectFieldAccessor(cachingConnectionFactory);
    List<?> channels = (List<?>) dfa.getPropertyValue("cachedChannelsTransactional");
    assertEquals(0, channels.size());

    container.stop();
  }
  /**
   * Verifies that the listener channel is not exposed when so configured and up-stack
   * RabbitTemplate uses the additional channel. created when exposeListenerChannel is false
   * (ChannelAwareMessageListener).
   */
  @SuppressWarnings("unchecked")
  @Test
  public void testChannelAwareMessageListenerDontExpose() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    final Channel firstChannel = mock(Channel.class);
    when(firstChannel.isOpen()).thenReturn(true);
    final Channel secondChannel = mock(Channel.class);
    when(secondChannel.isOpen()).thenReturn(true);

    final SingleConnectionFactory singleConnectionFactory =
        new SingleConnectionFactory(mockConnectionFactory);

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

    final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();

    doAnswer(
            new Answer<Channel>() {
              boolean done;

              @Override
              public Channel answer(InvocationOnMock invocation) throws Throwable {
                if (!done) {
                  done = true;
                  return firstChannel;
                }
                return secondChannel;
              }
            })
        .when(mockConnection)
        .createChannel();

    final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();

    doAnswer(
            new Answer<String>() {

              @Override
              public String answer(InvocationOnMock invocation) throws Throwable {
                consumer.set((Consumer) invocation.getArguments()[6]);
                return null;
              }
            })
        .when(firstChannel)
        .basicConsume(
            anyString(),
            anyBoolean(),
            anyString(),
            anyBoolean(),
            anyBoolean(),
            anyMap(),
            any(Consumer.class));

    final CountDownLatch commitLatch = new CountDownLatch(1);
    doAnswer(
            new Answer<String>() {

              @Override
              public String answer(InvocationOnMock invocation) throws Throwable {
                commitLatch.countDown();
                return null;
              }
            })
        .when(firstChannel)
        .txCommit();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Channel> exposed = new AtomicReference<Channel>();
    SimpleMessageListenerContainer container =
        new SimpleMessageListenerContainer(singleConnectionFactory);
    container.setMessageListener(
        new ChannelAwareMessageListener() {
          @Override
          public void onMessage(Message message, Channel channel) {
            exposed.set(channel);
            RabbitTemplate rabbitTemplate = new RabbitTemplate(singleConnectionFactory);
            rabbitTemplate.setChannelTransacted(true);
            // should use same channel as container
            rabbitTemplate.convertAndSend("foo", "bar", "baz");
            latch.countDown();
          }
        });
    container.setQueueNames("queue");
    container.setChannelTransacted(true);
    container.setExposeListenerChannel(false);
    container.setShutdownTimeout(100);
    container.afterPropertiesSet();
    container.start();

    consumer
        .get()
        .handleDelivery(
            "qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] {0});

    assertTrue(latch.await(10, TimeUnit.SECONDS));

    Exception e = tooManyChannels.get();
    if (e != null) {
      throw e;
    }

    // once for listener, once for exposed + 0 for template (used bound)
    verify(mockConnection, Mockito.times(2)).createChannel();
    assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
    verify(firstChannel).txCommit();
    verify(secondChannel).txCommit();
    verify(secondChannel)
        .basicPublish(
            Mockito.anyString(),
            Mockito.anyString(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));

    assertSame(secondChannel, exposed.get());

    verify(firstChannel, Mockito.never()).close();
    verify(secondChannel, Mockito.times(1)).close();
    container.stop();
  }
Esempio n. 12
0
 public boolean isConnected() {
   return connection != null && connection.isOpen() && channel != null && channel.isOpen();
 }
Esempio n. 13
0
 private void expectChannelRecovery(Channel ch) throws InterruptedException {
   assertTrue(ch.isOpen());
 }