Example usage for org.springframework.amqp.rabbit.connection Connection createChannel

List of usage examples for org.springframework.amqp.rabbit.connection Connection createChannel

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.connection Connection createChannel.

Prototype

Channel createChannel(boolean transactional) throws AmqpException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

From source file:org.springframework.amqp.rabbit.connection.AbstractConnectionFactoryTests.java

@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(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection1, 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(any(ExecutorService.class), anyString());
    verify(mockConnection2, times(1)).createChannel();

    connectionFactory.destroy();//  w  w  w  .java 2 s  . co m
    verify(mockConnection2, times(1)).close(anyInt());

}

From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java

@Test
public void testWithConnectionFactoryCachedConnection() throws Exception {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);

    final List<com.rabbitmq.client.Connection> mockConnections = new ArrayList<com.rabbitmq.client.Connection>();
    final List<Channel> mockChannels = new ArrayList<Channel>();

    doAnswer(new Answer<com.rabbitmq.client.Connection>() {

        private int connectionNumber;

        @Override/*w ww .  j a  va 2 s . com*/
        public com.rabbitmq.client.Connection answer(InvocationOnMock invocation) throws Throwable {
            com.rabbitmq.client.Connection connection = mock(com.rabbitmq.client.Connection.class);
            doAnswer(new Answer<Channel>() {

                private int channelNumber;

                @Override
                public Channel answer(InvocationOnMock invocation) throws Throwable {
                    Channel channel = mock(Channel.class);
                    when(channel.isOpen()).thenReturn(true);
                    int channelNumnber = ++this.channelNumber;
                    when(channel.toString())
                            .thenReturn("mockChannel" + connectionNumber + ":" + channelNumnber);
                    mockChannels.add(channel);
                    return channel;
                }
            }).when(connection).createChannel();
            int connectionNumber = ++this.connectionNumber;
            when(connection.toString()).thenReturn("mockConnection" + connectionNumber);
            when(connection.isOpen()).thenReturn(true);
            mockConnections.add(connection);
            return connection;
        }
    }).when(mockConnectionFactory).newConnection(any(ExecutorService.class), anyString());

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setExecutor(mock(ExecutorService.class));
    ccf.setCacheMode(CacheMode.CONNECTION);
    ccf.afterPropertiesSet();

    Set<?> allocatedConnections = TestUtils.getPropertyValue(ccf, "allocatedConnections", Set.class);
    assertEquals(0, allocatedConnections.size());
    BlockingQueue<?> idleConnections = TestUtils.getPropertyValue(ccf, "idleConnections", BlockingQueue.class);
    assertEquals(0, idleConnections.size());

    final AtomicReference<com.rabbitmq.client.Connection> createNotification = new AtomicReference<com.rabbitmq.client.Connection>();
    final AtomicReference<com.rabbitmq.client.Connection> closedNotification = new AtomicReference<com.rabbitmq.client.Connection>();
    ccf.setConnectionListeners(Collections.singletonList(new ConnectionListener() {

        @Override
        public void onCreate(Connection connection) {
            assertNull(createNotification.get());
            createNotification.set(targetDelegate(connection));
        }

        @Override
        public void onClose(Connection connection) {
            assertNull(closedNotification.get());
            closedNotification.set(targetDelegate(connection));
        }
    }));

    Connection con1 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con1);
    assertEquals(1, allocatedConnections.size());
    assertEquals(0, idleConnections.size());
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(0), createNotification.getAndSet(null));

    Channel channel1 = con1.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel1);
    channel1.close();
    //AMQP-358
    verify(mockChannels.get(0), never()).close();

    con1.close(); // should be ignored, and placed into connection cache.
    verify(mockConnections.get(0), never()).close();
    assertEquals(1, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    assertNull(closedNotification.get());

    /*
     * will retrieve same connection that was just put into cache, and reuse single channel from cache as well
     */
    Connection con2 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con2);
    Channel channel2 = con2.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel2);
    channel2.close();
    verify(mockChannels.get(0), never()).close();
    con2.close();
    verify(mockConnections.get(0), never()).close();
    assertEquals(1, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    assertNull(createNotification.get());

    /*
     * Now check for multiple connections/channels
     */
    con1 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con1);
    con2 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(1), con2);
    channel1 = con1.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel1);
    channel2 = con2.createChannel(false);
    verifyChannelIs(mockChannels.get(1), channel2);
    assertEquals(2, allocatedConnections.size());
    assertEquals(0, idleConnections.size());
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(1), createNotification.getAndSet(null));

    // put mock1 in cache
    channel1.close();
    verify(mockChannels.get(1), never()).close();
    con1.close();
    verify(mockConnections.get(0), never()).close();
    assertEquals(2, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    assertNull(closedNotification.get());

    Connection con3 = ccf.createConnection();
    assertNull(createNotification.get());
    verifyConnectionIs(mockConnections.get(0), con3);
    Channel channel3 = con3.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel3);

    assertEquals(2, allocatedConnections.size());
    assertEquals(0, idleConnections.size());

    channel2.close();
    con2.close();
    assertEquals(2, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    channel3.close();
    con3.close();
    assertEquals(2, allocatedConnections.size());
    assertEquals(2, idleConnections.size());
    assertEquals("1", ccf.getCacheProperties().get("openConnections"));
    /*
     *  Cache size is 1; con3 (mock1) should have been a real close.
     *  con2 (mock2) should still be in the cache.
     */
    verify(mockConnections.get(0)).close(30000);
    assertNotNull(closedNotification.get());
    assertSame(mockConnections.get(0), closedNotification.getAndSet(null));
    verify(mockChannels.get(1), never()).close();
    verify(mockConnections.get(1), never()).close(30000);
    verify(mockChannels.get(1), never()).close();
    verifyConnectionIs(mockConnections.get(1), idleConnections.iterator().next());
    /*
     * Now a closed cached connection
     */
    when(mockConnections.get(1).isOpen()).thenReturn(false);
    when(mockChannels.get(1).isOpen()).thenReturn(false);
    con3 = ccf.createConnection();
    assertNotNull(closedNotification.get());
    assertSame(mockConnections.get(1), closedNotification.getAndSet(null));
    verifyConnectionIs(mockConnections.get(2), con3);
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(2), createNotification.getAndSet(null));
    assertEquals(2, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    assertEquals("1", ccf.getCacheProperties().get("openConnections"));
    channel3 = con3.createChannel(false);
    verifyChannelIs(mockChannels.get(2), channel3);
    channel3.close();
    con3.close();
    assertNull(closedNotification.get());
    assertEquals(2, allocatedConnections.size());
    assertEquals(2, idleConnections.size());
    assertEquals("1", ccf.getCacheProperties().get("openConnections"));

    /*
     * Now a closed cached connection when creating a channel
     */
    con3 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(2), con3);
    assertNull(createNotification.get());
    assertEquals(2, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    when(mockConnections.get(2).isOpen()).thenReturn(false);
    channel3 = con3.createChannel(false);
    assertNotNull(closedNotification.getAndSet(null));
    assertNotNull(createNotification.getAndSet(null));

    verifyChannelIs(mockChannels.get(3), channel3);
    channel3.close();
    con3.close();
    assertNull(closedNotification.get());
    assertEquals(2, allocatedConnections.size());
    assertEquals(2, idleConnections.size());
    assertEquals("1", ccf.getCacheProperties().get("openConnections"));

    // destroy
    ccf.destroy();
    assertNotNull(closedNotification.get());
    verify(mockConnections.get(3)).close(30000);
}

From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java

@Test
public void testWithConnectionFactoryCachedConnectionAndChannels() throws Exception {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);

    final List<com.rabbitmq.client.Connection> mockConnections = new ArrayList<com.rabbitmq.client.Connection>();
    final List<Channel> mockChannels = new ArrayList<Channel>();

    doAnswer(new Answer<com.rabbitmq.client.Connection>() {

        private int connectionNumber;

        @Override//from   w ww .ja  v  a 2s .c  om
        public com.rabbitmq.client.Connection answer(InvocationOnMock invocation) throws Throwable {
            com.rabbitmq.client.Connection connection = mock(com.rabbitmq.client.Connection.class);
            doAnswer(new Answer<Channel>() {

                private int channelNumber;

                @Override
                public Channel answer(InvocationOnMock invocation) throws Throwable {
                    Channel channel = mock(Channel.class);
                    when(channel.isOpen()).thenReturn(true);
                    int channelNumnber = ++this.channelNumber;
                    when(channel.toString())
                            .thenReturn("mockChannel" + connectionNumber + ":" + channelNumnber);
                    mockChannels.add(channel);
                    return channel;
                }
            }).when(connection).createChannel();
            int connectionNumber = ++this.connectionNumber;
            when(connection.toString()).thenReturn("mockConnection" + connectionNumber);
            when(connection.isOpen()).thenReturn(true);
            mockConnections.add(connection);
            return connection;
        }
    }).when(mockConnectionFactory).newConnection(any(ExecutorService.class), anyString());

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setExecutor(mock(ExecutorService.class));
    ccf.setCacheMode(CacheMode.CONNECTION);
    ccf.setConnectionCacheSize(2);
    ccf.setChannelCacheSize(2);
    ccf.afterPropertiesSet();

    Set<?> allocatedConnections = TestUtils.getPropertyValue(ccf, "allocatedConnections", Set.class);
    assertEquals(0, allocatedConnections.size());
    BlockingQueue<?> idleConnections = TestUtils.getPropertyValue(ccf, "idleConnections", BlockingQueue.class);
    assertEquals(0, idleConnections.size());
    @SuppressWarnings("unchecked")
    Map<?, List<?>> cachedChannels = TestUtils.getPropertyValue(ccf,
            "allocatedConnectionNonTransactionalChannels", Map.class);

    final AtomicReference<com.rabbitmq.client.Connection> createNotification = new AtomicReference<com.rabbitmq.client.Connection>();
    final AtomicReference<com.rabbitmq.client.Connection> closedNotification = new AtomicReference<com.rabbitmq.client.Connection>();
    ccf.setConnectionListeners(Collections.singletonList(new ConnectionListener() {

        @Override
        public void onCreate(Connection connection) {
            assertNull(createNotification.get());
            createNotification.set(targetDelegate(connection));
        }

        @Override
        public void onClose(Connection connection) {
            assertNull(closedNotification.get());
            closedNotification.set(targetDelegate(connection));
        }
    }));

    Connection con1 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con1);
    assertEquals(1, allocatedConnections.size());
    assertEquals(0, idleConnections.size());
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(0), createNotification.getAndSet(null));

    Channel channel1 = con1.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel1);
    channel1.close();
    //AMQP-358
    verify(mockChannels.get(0), never()).close();

    con1.close(); // should be ignored, and placed into connection cache.
    verify(mockConnections.get(0), never()).close();
    assertEquals(1, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    assertEquals(1, cachedChannels.get(con1).size());
    assertNull(closedNotification.get());

    /*
     * will retrieve same connection that was just put into cache, and reuse single channel from cache as well
     */
    Connection con2 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con2);
    Channel channel2 = con2.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel2);
    channel2.close();
    verify(mockChannels.get(0), never()).close();
    con2.close();
    verify(mockConnections.get(0), never()).close();
    assertEquals(1, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    assertNull(createNotification.get());

    /*
     * Now check for multiple connections/channels
     */
    con1 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con1);
    con2 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(1), con2);
    channel1 = con1.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel1);
    channel2 = con2.createChannel(false);
    verifyChannelIs(mockChannels.get(1), channel2);
    assertEquals(2, allocatedConnections.size());
    assertEquals(0, idleConnections.size());
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(1), createNotification.getAndSet(null));

    // put mock1 in cache
    channel1.close();
    verify(mockChannels.get(1), never()).close();
    con1.close();
    verify(mockConnections.get(0), never()).close();
    assertEquals(2, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    assertNull(closedNotification.get());

    Connection con3 = ccf.createConnection();
    assertNull(createNotification.get());
    verifyConnectionIs(mockConnections.get(0), con3);
    Channel channel3 = con3.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel3);

    assertEquals(2, allocatedConnections.size());
    assertEquals(0, idleConnections.size());

    channel2.close();
    con2.close();
    assertEquals(2, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    channel3.close();
    con3.close();
    assertEquals(2, allocatedConnections.size());
    assertEquals(2, idleConnections.size());
    assertEquals(1, cachedChannels.get(con1).size());
    assertEquals(1, cachedChannels.get(con2).size());
    /*
     *  Cache size is 2; neither should have been a real close.
     *  con2 (mock2) and con1 should still be in the cache.
     */
    verify(mockConnections.get(0), never()).close(30000);
    assertNull(closedNotification.get());
    verify(mockChannels.get(1), never()).close();
    verify(mockConnections.get(1), never()).close(30000);
    verify(mockChannels.get(1), never()).close();
    assertEquals(2, idleConnections.size());
    Iterator<?> iterator = idleConnections.iterator();
    verifyConnectionIs(mockConnections.get(1), iterator.next());
    verifyConnectionIs(mockConnections.get(0), iterator.next());
    /*
     * Now a closed cached connection
     */
    when(mockConnections.get(1).isOpen()).thenReturn(false);
    con3 = ccf.createConnection();
    assertNotNull(closedNotification.get());
    assertSame(mockConnections.get(1), closedNotification.getAndSet(null));
    verifyConnectionIs(mockConnections.get(0), con3);
    assertNull(createNotification.get());
    assertEquals(2, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    channel3 = con3.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel3);
    channel3.close();
    con3.close();
    assertNull(closedNotification.get());
    assertEquals(2, allocatedConnections.size());
    assertEquals(2, idleConnections.size());

    /*
     * Now a closed cached connection when creating a channel
     */
    con3 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con3);
    assertNull(createNotification.get());
    assertEquals(2, allocatedConnections.size());
    assertEquals(1, idleConnections.size());
    when(mockConnections.get(0).isOpen()).thenReturn(false);
    channel3 = con3.createChannel(false);
    assertNotNull(closedNotification.getAndSet(null));
    assertNotNull(createNotification.getAndSet(null));

    verifyChannelIs(mockChannels.get(2), channel3);
    channel3.close();
    con3.close();
    assertNull(closedNotification.get());
    assertEquals(2, allocatedConnections.size());
    assertEquals(2, idleConnections.size());

    Connection con4 = ccf.createConnection();
    assertSame(con3, con4);
    assertEquals(1, idleConnections.size());
    Channel channelA = con4.createChannel(false);
    Channel channelB = con4.createChannel(false);
    Channel channelC = con4.createChannel(false);
    channelA.close();
    assertEquals(1, cachedChannels.get(con4).size());
    channelB.close();
    assertEquals(2, cachedChannels.get(con4).size());
    channelC.close();
    assertEquals(2, cachedChannels.get(con4).size());

    // destroy
    ccf.destroy();
    assertNotNull(closedNotification.get());
    // physical wasn't invoked, because this mockConnection marked with 'false' for 'isOpen()'
    verify(mockConnections.get(0)).close(30000);
    verify(mockConnections.get(1)).close(30000);
    verify(mockConnections.get(2)).close(30000);
}

From source file:org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.java

/**
 * Obtain a RabbitMQ Channel that is synchronized with the current
 * transaction, if any.//from w  w  w. j ava  2s. c om
 * 
 * @param connectionFactory
 *            the ConnectionFactory to obtain a Channel for
 * @param synchedLocalTransactionAllowed
 *            whether to allow for a local RabbitMQ transaction that is
 *            synchronized with a Spring-managed transaction (where the main
 *            transaction might be a JDBC-based one for a specific
 *            DataSource, for example), with the RabbitMQ transaction
 *            committing right after the main transaction. If not allowed,
 *            the given ConnectionFactory needs to handle transaction
 *            enlistment underneath the covers.
 * @return the transactional Channel, or <code>null</code> if none found
 */
public static RabbitResourceHolder getTransactionalResourceHolder(final ConnectionFactory connectionFactory,
        final boolean synchedLocalTransactionAllowed) {

    RabbitResourceHolder holder = doGetTransactionalResourceHolder(connectionFactory, new ResourceFactory() {
        public Channel getChannel(RabbitResourceHolder holder) {
            return holder.getChannel();
        }

        public Connection getConnection(RabbitResourceHolder holder) {
            return holder.getConnection();
        }

        public Connection createConnection() throws IOException {
            return connectionFactory.createConnection();
        }

        public Channel createChannel(Connection con) throws IOException {
            return con.createChannel(synchedLocalTransactionAllowed);
        }

        public boolean isSynchedLocalTransactionAllowed() {
            return synchedLocalTransactionAllowed;
        }
    });
    return holder;
}

From source file:org.springframework.amqp.rabbit.connection.LocalizedQueueConnectionFactoryTests.java

@SuppressWarnings("unchecked")
private ConnectionFactory mockCF(final String address, final CountDownLatch latch) throws Exception {
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    Connection connection = mock(Connection.class);
    Channel channel = mock(Channel.class);
    when(connectionFactory.createConnection()).thenReturn(connection);
    when(connection.createChannel(false)).thenReturn(channel);
    when(connection.isOpen()).thenReturn(true, false);
    when(channel.isOpen()).thenReturn(true, false);
    doAnswer(invocation -> {//from   www  . j  a v a2 s.  c  o  m
        String tag = UUID.randomUUID().toString();
        consumers.put(address, (Consumer) invocation.getArguments()[6]);
        consumerTags.put(address, tag);
        if (latch != null) {
            latch.countDown();
        }
        return tag;
    }).when(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            any(Consumer.class));
    when(connectionFactory.getHost()).thenReturn(address);
    this.channels.put(address, channel);
    return connectionFactory;
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.java

private void doConsumeFromQueue(String queue) {
    if (!isActive()) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Consume from queue " + queue + " ignore, container stopping");
        }/*from ww w . j a  va2s  .c  o m*/
        return;
    }
    Connection connection = null;
    try {
        connection = getConnectionFactory().createConnection();
    } catch (Exception e) {
        this.consumersToRestart.add(new SimpleConsumer(null, null, queue));
        throw new AmqpConnectException(e);
    }
    Channel channel = null;
    SimpleConsumer consumer = null;
    try {
        channel = connection.createChannel(isChannelTransacted());
        channel.basicQos(getPrefetchCount());
        consumer = new SimpleConsumer(connection, channel, queue);
        channel.queueDeclarePassive(queue);
        consumer.consumerTag = channel.basicConsume(queue, getAcknowledgeMode().isAutoAck(),
                (getConsumerTagStrategy() != null ? getConsumerTagStrategy().createConsumerTag(queue) : ""),
                false, isExclusive(), getConsumerArguments(), consumer);
    } catch (IOException e) {
        if (channel != null) {
            RabbitUtils.closeChannel(channel);
        }
        if (connection != null) {
            RabbitUtils.closeConnection(connection);
        }
        if (e.getCause() instanceof ShutdownSignalException
                && e.getCause().getMessage().contains("in exclusive use")) {
            getExclusiveConsumerExceptionLogger().log(logger, "Exclusive consumer failure", e.getCause());
            publishConsumerFailedEvent("Consumer raised exception, attempting restart", false, e);
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug("Queue not present or basicConsume failed, scheduling consumer " + consumer
                    + " for restart");
        }
        this.consumersToRestart.add(consumer);
        consumer = null;
    }
    synchronized (this.consumersMonitor) {
        if (consumer != null) {
            this.cancellationLock.add(consumer);
            this.consumers.add(consumer);
            this.consumersByQueue.add(queue, consumer);
            if (this.logger.isInfoEnabled()) {
                this.logger.info(consumer + " started");
            }
        }
    }
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerIntegrationTests.java

@Test
public void testRecoverBrokerLoss() throws Exception {
    ConnectionFactory mockCF = mock(ConnectionFactory.class);
    Connection connection = mock(Connection.class);
    Channel channel = mock(Channel.class);
    given(connection.isOpen()).willReturn(true);
    given(mockCF.createConnection()).willReturn(connection);
    given(connection.createChannel(false)).willReturn(channel);
    given(channel.isOpen()).willReturn(true);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(2);
    ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class);
    final String tag = "tag";
    willAnswer(i -> {/*  w ww. j a  v a 2s .  co  m*/
        latch1.countDown();
        latch2.countDown();
        return tag;
    }).given(channel).basicConsume(eq("foo"), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            consumerCaptor.capture());
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(mockCF);
    container.setQueueNames("foo");
    container.setBeanName("brokerLost");
    container.setConsumerTagStrategy(q -> "tag");
    container.setShutdownTimeout(1);
    container.setMonitorInterval(200);
    container.setFailedDeclarationRetryInterval(200);
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    given(channel.isOpen()).willReturn(false);
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    container.setShutdownTimeout(1);
    container.stop();
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerIntegrationTests.java

@Test
public void testCancelConsumerBeforeConsumeOk() throws Exception {
    ConnectionFactory mockCF = mock(ConnectionFactory.class);
    Connection connection = mock(Connection.class);
    Channel channel = mock(Channel.class);
    given(connection.isOpen()).willReturn(true);
    given(mockCF.createConnection()).willReturn(connection);
    given(connection.createChannel(false)).willReturn(channel);
    given(channel.isOpen()).willReturn(true);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class);
    final String tag = "tag";
    willAnswer(i -> {//from  w ww . ja va2  s .co m
        latch1.countDown();
        return tag;
    }).given(channel).basicConsume(eq("foo"), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            consumerCaptor.capture());
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(mockCF);
    container.setQueueNames("foo");
    container.setBeanName("backOff");
    container.setConsumerTagStrategy(q -> "tag");
    container.setShutdownTimeout(1);
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    Consumer consumer = consumerCaptor.getValue();
    Executors.newSingleThreadExecutor().execute(() -> {
        container.stop();
        latch2.countDown();
    });
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    verify(channel).basicCancel(tag); // canceled properly even without consumeOk
    consumer.handleCancelOk(tag);
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerTests.java

@SuppressWarnings("unchecked")
@Test//  www  .jav a  2s .com
public void testRecoverBrokerLoss() throws Exception {
    ConnectionFactory mockCF = mock(ConnectionFactory.class);
    Connection connection = mock(Connection.class);
    Channel channel = mock(Channel.class);
    given(connection.isOpen()).willReturn(true);
    given(mockCF.createConnection()).willReturn(connection);
    given(connection.createChannel(false)).willReturn(channel);
    given(channel.isOpen()).willReturn(true);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(2);
    ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class);
    final String tag = "tag";
    willAnswer(i -> {
        latch1.countDown();
        latch2.countDown();
        return tag;
    }).given(channel).basicConsume(eq("foo"), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            consumerCaptor.capture());
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(mockCF);
    container.setQueueNames("foo");
    container.setBeanName("brokerLost");
    container.setConsumerTagStrategy(q -> "tag");
    container.setShutdownTimeout(1);
    container.setMonitorInterval(200);
    container.setFailedDeclarationRetryInterval(200);
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    given(channel.isOpen()).willReturn(false);
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    container.setShutdownTimeout(1);
    container.stop();
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerTests.java

@SuppressWarnings("unchecked")
@Test/*from   ww  w  .j a v  a2  s.c  o  m*/
public void testCancelConsumerBeforeConsumeOk() throws Exception {
    ConnectionFactory mockCF = mock(ConnectionFactory.class);
    Connection connection = mock(Connection.class);
    Channel channel = mock(Channel.class);
    given(connection.isOpen()).willReturn(true);
    given(mockCF.createConnection()).willReturn(connection);
    given(connection.createChannel(false)).willReturn(channel);
    given(channel.isOpen()).willReturn(true);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class);
    final String tag = "tag";
    willAnswer(i -> {
        latch1.countDown();
        return tag;
    }).given(channel).basicConsume(eq("foo"), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            consumerCaptor.capture());
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(mockCF);
    container.setQueueNames("foo");
    container.setBeanName("backOff");
    container.setConsumerTagStrategy(q -> "tag");
    container.setShutdownTimeout(1);
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    Consumer consumer = consumerCaptor.getValue();
    Executors.newSingleThreadExecutor().execute(() -> {
        container.stop();
        latch2.countDown();
    });
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    verify(channel).basicCancel(tag); // canceled properly even without consumeOk
    consumer.handleCancelOk(tag);
}