Example usage for org.springframework.amqp.rabbit.connection ConnectionListener ConnectionListener

List of usage examples for org.springframework.amqp.rabbit.connection ConnectionListener ConnectionListener

Introduction

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

Prototype

ConnectionListener

Source Link

Usage

From source file:org.resthub.rpc.RPCEndpoint.java

/**
 * Starts the endpoint on the connection specified.
 * A listener container is launched on a created queue. The listener will
 * respond to hessian requests. The endpoint is closed by calling the destroy 
 * method.//from   w  w w . j  a va 2  s.com
 */
public void run() {
    logger.debug("Launching endpoint for service : " + serviceAPI.getSimpleName());
    admin = new RabbitAdmin(connectionFactory);
    // Add connectionListener to recreate queue when connection fall
    connectionFactory.addConnectionListener(new ConnectionListener() {
        public void onCreate(Connection connection) {
            createQueue(admin, getRequestQueueName(serviceAPI));
        }

        public void onClose(Connection connection) {
        }

    });

    // Create the queue normaly the first time
    this.createQueue(admin, getRequestQueueName(serviceAPI));

    MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(
            new RawMessageDelegate(serviceAPI, serviceImpl, serializationHandler));
    listenerAdapter.setMessageConverter(null);
    listenerAdapter.setMandatoryPublish(false);

    listenerContainer = new SimpleMessageListenerContainer();
    listenerContainer.setConnectionFactory(connectionFactory);
    listenerContainer.setQueueNames(getRequestQueueName(serviceAPI));
    listenerContainer.setMessageListener(listenerAdapter);
    if (this.concurentConsumers > 0) {
        listenerContainer.setConcurrentConsumers(concurentConsumers);
    }
    listenerContainer.start();
}

From source file:org.resthub.rpc.HessianEndpoint.java

/**
 * Starts the endpoint on the connection specified.
 * A listener container is launched on a created queue. The listener will
 * respond to hessian requests. The endpoint is closed by calling the destroy 
 * method./*from  w  w w . j a va2 s.  c o m*/
 */
public void run() {
    logger.debug("Launching endpoint for service : " + serviceAPI.getSimpleName());
    admin = new RabbitAdmin(connectionFactory);
    // Add connectionListener to recreate queue when connection fall
    connectionFactory.addConnectionListener(new ConnectionListener() {
        public void onCreate(Connection connection) {
            createQueue(admin, getRequestQueueName(serviceAPI));
        }

        public void onClose(Connection connection) {
        }

    });

    // Create the queue normaly the first time
    this.createQueue(admin, getRequestQueueName(serviceAPI));

    MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(
            new RawMessageDelegate(serviceAPI, serviceImpl, serializerFactory));
    listenerAdapter.setMessageConverter(null);
    listenerAdapter.setMandatoryPublish(false);

    listenerContainer = new SimpleMessageListenerContainer();
    listenerContainer.setConnectionFactory(connectionFactory);
    listenerContainer.setQueueNames(getRequestQueueName(serviceAPI));
    listenerContainer.setMessageListener(listenerAdapter);
    if (this.concurentConsumers > 0) {
        listenerContainer.setConcurrentConsumers(concurentConsumers);
    }
    listenerContainer.start();
}

From source file:org.resthub.rpc.AMQPHessianProxyFactory.java

public void afterPropertiesSet() {
    if (this.connectionFactory == null) {
        throw new IllegalArgumentException("Property 'connectionFactory' is required");
    }// w  ww  .  ja v  a2  s  .  co  m
    // initialize template
    this.template = new RabbitTemplate(this.connectionFactory);
    if (this.readTimeout > 0) {
        this.template.setReplyTimeout(readTimeout);
    }
    this.initializeQueues();

    // Add connection listener to recreate queue and reinitialize template when connection fall
    connectionFactory.addConnectionListener(new ConnectionListener() {

        public void onCreate(Connection connection) {
            initializeQueues();
        }

        public void onClose(Connection connection) {
        }

    });
}

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

@Test
public void testWithListener() throws Exception {

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

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection);

    final AtomicInteger called = new AtomicInteger(0);
    AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory);
    connectionFactory.setConnectionListeners(Collections.singletonList(new ConnectionListener() {

        @Override/*w  w w  . ja  v a 2  s  .  c o  m*/
        public void onCreate(Connection connection) {
            called.incrementAndGet();
        }

        @Override
        public void onClose(Connection connection) {
            called.decrementAndGet();
        }

    }));

    Log logger = spy(TestUtils.getPropertyValue(connectionFactory, "logger", Log.class));
    doReturn(true).when(logger).isInfoEnabled();
    new DirectFieldAccessor(connectionFactory).setPropertyValue("logger", logger);
    Connection con = connectionFactory.createConnection();
    assertEquals(1, called.get());
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(logger).info(captor.capture());
    assertThat(captor.getValue(), containsString("Created new connection: SimpleConnection"));

    con.close();
    assertEquals(1, called.get());
    verify(mockConnection, never()).close(anyInt());

    connectionFactory.createConnection();
    assertEquals(1, called.get());

    connectionFactory.destroy();
    assertEquals(0, called.get());
    verify(mockConnection, atLeastOnce()).close(anyInt());

    verify(mockConnectionFactory, times(1)).newConnection(any(ExecutorService.class), anyString());

}

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

@Test
public void testWithListenerRegisteredAfterOpen() throws Exception {

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

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection);

    final AtomicInteger called = new AtomicInteger(0);
    AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory);
    Connection con = connectionFactory.createConnection();
    assertEquals(0, called.get());/*  w ww  .  ja  v  a  2s .c o m*/

    connectionFactory.setConnectionListeners(Collections.singletonList(new ConnectionListener() {

        @Override
        public void onCreate(Connection connection) {
            called.incrementAndGet();
        }

        @Override
        public void onClose(Connection connection) {
            called.decrementAndGet();
        }

    }));
    assertEquals(1, called.get());

    con.close();
    assertEquals(1, called.get());
    verify(mockConnection, never()).close(anyInt());

    connectionFactory.createConnection();
    assertEquals(1, called.get());

    connectionFactory.destroy();
    assertEquals(0, called.get());
    verify(mockConnection, atLeastOnce()).close(anyInt());

    verify(mockConnectionFactory, times(1)).newConnection(any(ExecutorService.class), anyString());

}

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

@Test
public void testWithConnectionListener() throws Exception {

    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection1 = mock(com.rabbitmq.client.Connection.class);
    when(mockConnection1.toString()).thenReturn("conn1");
    com.rabbitmq.client.Connection mockConnection2 = mock(com.rabbitmq.client.Connection.class);
    when(mockConnection2.toString()).thenReturn("conn2");
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection1, mockConnection2);
    when(mockConnection1.isOpen()).thenReturn(true);
    when(mockChannel.isOpen()).thenReturn(true);
    when(mockConnection1.createChannel()).thenReturn(mockChannel);
    when(mockConnection2.createChannel()).thenReturn(mockChannel);

    final AtomicReference<Connection> created = new AtomicReference<Connection>();
    final AtomicReference<Connection> closed = new AtomicReference<Connection>();
    final AtomicInteger timesClosed = new AtomicInteger(0);
    AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory);
    connectionFactory.addConnectionListener(new ConnectionListener() {

        @Override//from   w  ww. j  a v a  2  s .com
        public void onCreate(Connection connection) {
            created.set(connection);
        }

        @Override
        public void onClose(Connection connection) {
            closed.set(connection);
            timesClosed.getAndAdd(1);
        }
    });
    ((CachingConnectionFactory) connectionFactory).setChannelCacheSize(1);

    Connection con = connectionFactory.createConnection();
    Channel channel = con.createChannel(false);
    assertSame(con, created.get());
    channel.close();

    con.close();
    verify(mockConnection1, never()).close();

    Connection same = connectionFactory.createConnection();
    channel = con.createChannel(false);
    assertSame(con, same);
    channel.close();
    com.rabbitmq.client.Connection conDelegate = targetDelegate(con);

    when(mockConnection1.isOpen()).thenReturn(false);
    when(mockChannel.isOpen()).thenReturn(false); // force a connection refresh
    channel.basicCancel("foo");
    channel.close();
    assertEquals(1, timesClosed.get());

    Connection notSame = connectionFactory.createConnection();
    assertNotSame(conDelegate, targetDelegate(notSame));
    assertSame(con, closed.get());
    assertSame(notSame, created.get());

    connectionFactory.destroy();
    verify(mockConnection2, atLeastOnce()).close(anyInt());
    assertSame(notSame, closed.get());
    assertEquals(2, timesClosed.get());

    verify(mockConnectionFactory, times(2)).newConnection(any(ExecutorService.class), anyString());
}

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  w w .  j  av a 2  s  .  c o  m
        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 ww w  .  j ava  2  s .  c o m
        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.core.RabbitAdmin.java

/**
 * If {@link #setAutoStartup(boolean) autoStartup} is set to true, registers a callback on the
 * {@link ConnectionFactory} to declare all exchanges and queues in the enclosing application context. If the
 * callback fails then it may cause other clients of the connection factory to fail, but since only exchanges,
 * queues and bindings are declared failure is not expected.
 *
 * @see InitializingBean#afterPropertiesSet()
 * @see #initialize()// w w w.  j  a v a 2  s  .co m
 */
public void afterPropertiesSet() {

    synchronized (this.lifecycleMonitor) {

        if (this.running || !this.autoStartup) {
            return;
        }

        connectionFactory.addConnectionListener(new ConnectionListener() {

            // Prevent stack overflow...
            private AtomicBoolean initializing = new AtomicBoolean(false);

            public void onCreate(Connection connection) {
                if (!initializing.compareAndSet(false, true)) {
                    // If we are already initializing, we don't need to do it again...
                    return;
                }
                try {
                    /*
                     * ...but it is possible for this to happen twice in the same ConnectionFactory (if more than
                     * one concurrent Connection is allowed). It's idempotent, so no big deal (a bit of network
                     * chatter). In fact it might even be a good thing: exclusive queues only make sense if they are
                     * declared for every connection. If anyone has a problem with it: use auto-startup="false".
                     */
                    initialize();
                } finally {
                    initializing.compareAndSet(true, false);
                }
            }

            public void onClose(Connection connection) {
            }

        });

        this.running = true;

    }
}