Example usage for org.springframework.amqp.rabbit.connection CachingConnectionFactory destroy

List of usage examples for org.springframework.amqp.rabbit.connection CachingConnectionFactory destroy

Introduction

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

Prototype

@Override
public final void destroy() 

Source Link

Document

Close the underlying shared connection.

Usage

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

@Test
public void testDoubleLogicalClose() throws Exception {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection1 = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel1 = mock(Channel.class);

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

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

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setExecutor(mock(ExecutorService.class));
    ccf.setChannelCacheSize(1);//from  ww  w  .  j  av  a  2 s . c  o m
    ccf.setChannelCheckoutTimeout(10);

    Connection con = ccf.createConnection();

    Channel channel1 = con.createChannel(false);
    assertEquals(0, ((Semaphore) TestUtils.getPropertyValue(ccf, "checkoutPermits", Map.class).values()
            .iterator().next()).availablePermits());
    channel1.close();

    assertEquals(1, ((Semaphore) TestUtils.getPropertyValue(ccf, "checkoutPermits", Map.class).values()
            .iterator().next()).availablePermits());

    channel1.close(); // double close of proxy

    assertEquals(1, ((Semaphore) TestUtils.getPropertyValue(ccf, "checkoutPermits", Map.class).values()
            .iterator().next()).availablePermits());

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

    ccf.destroy();

    assertEquals(1, ((Semaphore) TestUtils.getPropertyValue(ccf, "checkoutPermits", Map.class).values()
            .iterator().next()).availablePermits());

}

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

@Test
public void testWithConnectionFactoryDestroy() 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);

    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);
    Channel mockChannel3 = mock(Channel.class);

    assertNotSame(mockChannel1, mockChannel2);

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection1, mockConnection2);
    when(mockConnection1.createChannel()).thenReturn(mockChannel1, mockChannel2);
    when(mockConnection1.isOpen()).thenReturn(true);
    when(mockConnection2.createChannel()).thenReturn(mockChannel3);
    when(mockConnection2.isOpen()).thenReturn(true);
    // Called during physical close
    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);
    when(mockChannel3.isOpen()).thenReturn(true);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setExecutor(mock(ExecutorService.class));
    ccf.setChannelCacheSize(2);//from   w  w w  .jav  a  2 s .co  m

    Connection con = ccf.createConnection();

    // This will return a proxy that surpresses calls to close
    Channel channel1 = con.createChannel(false);
    Channel channel2 = con.createChannel(false);

    // Should be ignored, and add last into channel cache.
    channel1.close();
    channel2.close();

    // remove first entry in cache (channel1)
    Channel ch1 = con.createChannel(false);
    // remove first entry in cache (channel2)
    Channel ch2 = con.createChannel(false);

    assertSame(ch1, channel1);
    assertSame(ch2, channel2);

    Channel target1 = ((ChannelProxy) ch1).getTargetChannel();
    Channel target2 = ((ChannelProxy) ch2).getTargetChannel();

    // make sure mokito returned different mocks for the channel
    assertNotSame(target1, target2);

    ch1.close();
    ch2.close();
    con.close(); // should be ignored
    com.rabbitmq.client.Connection conDelegate = targetDelegate(con);

    ccf.destroy(); // should call close on connection and channels in cache

    verify(mockConnection1, times(2)).createChannel();

    verify(mockConnection1).close(anyInt());

    // verify(mockChannel1).close();
    verify(mockChannel2).close();

    // After destroy we can get a new connection
    Connection con1 = ccf.createConnection();
    assertNotSame(conDelegate, targetDelegate(con1));

    // This will return a proxy that surpresses calls to close
    Channel channel3 = con.createChannel(false);
    assertNotSame(channel3, channel1);
    assertNotSame(channel3, channel2);
}

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/*from  w ww. j  a  va2 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//  ww w . j a  va2 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.connection.CachingConnectionFactoryTests.java

@Test
public void testWithConnectionFactoryCachedConnectionIdleAreClosed() 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  a  v a  2s  .  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" + 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(5);
    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());

    Connection conn1 = ccf.createConnection();
    Connection conn2 = ccf.createConnection();
    Connection conn3 = ccf.createConnection();
    assertEquals(3, allocatedConnections.size());
    assertEquals(0, idleConnections.size());
    conn1.close();
    conn2.close();
    conn3.close();
    assertEquals(3, allocatedConnections.size());
    assertEquals(3, idleConnections.size());

    when(mockConnections.get(0).isOpen()).thenReturn(false);
    when(mockConnections.get(1).isOpen()).thenReturn(false);
    Connection conn4 = ccf.createConnection();
    assertEquals(3, allocatedConnections.size());
    assertEquals(2, idleConnections.size());
    assertSame(conn3, conn4);
    conn4.close();
    assertEquals(3, allocatedConnections.size());
    assertEquals(3, idleConnections.size());
    assertEquals("1", ccf.getCacheProperties().get("openConnections"));

    ccf.destroy();
    assertEquals(3, allocatedConnections.size());
    assertEquals(3, idleConnections.size());
    assertEquals("0", ccf.getCacheProperties().get("openConnections"));
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdminTests.java

@Test
public void testAvoidHangAMQP_508() {
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    RabbitAdmin admin = new RabbitAdmin(cf);
    String longName = new String(new byte[300]).replace('\u0000', 'x');
    try {//from  w w w  .j  av  a2s . co  m
        admin.declareQueue(new Queue(longName));
    } catch (Exception e) {
        e.printStackTrace();
    }
    String goodName = "foobar";
    admin.declareQueue(new Queue(goodName));
    assertNull(admin.getQueueProperties(longName));
    assertNotNull(admin.getQueueProperties(goodName));
    admin.deleteQueue(goodName);
    cf.destroy();
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests.java

@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(any(ExecutorService.class), anyString()))
            .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);/*from  w  ww.  j a v  a2 s .  co  m*/
    ccf.setChannelCacheSize(3);
    final RabbitTemplate template = new RabbitTemplate(ccf);

    final AtomicBoolean confirmed = new AtomicBoolean();
    template.setConfirmCallback((correlationData, ack, 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(() -> template.execute(channel -> {
        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));
    assertEquals(2, template.getUnconfirmedCount());
    Collection<CorrelationData> unconfirmed = template.getUnconfirmed(-1);
    assertEquals(2, unconfirmed.size());
    assertEquals(0, template.getUnconfirmedCount());
    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("publisherConfirmChannels");
    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());
}

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

@Test
public void testSimple() throws Exception {
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setThreadNamePrefix("client-");
    executor.afterPropertiesSet();//from  www .j  a v  a2  s .  c  o m
    cf.setExecutor(executor);
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setQueueNames(Q1, Q2);
    container.setConsumersPerQueue(2);
    container.setMessageListener(new MessageListenerAdapter((ReplyingMessageListener<String, String>) in -> {
        if ("foo".equals(in) || "bar".equals(in)) {
            return in.toUpperCase();
        } else {
            return null;
        }
    }));
    container.setBeanName("simple");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    RabbitTemplate template = new RabbitTemplate(cf);
    assertEquals("FOO", template.convertSendAndReceive(Q1, "foo"));
    assertEquals("BAR", template.convertSendAndReceive(Q2, "bar"));
    container.stop();
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size());
    template.stop();
    cf.destroy();
}

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

@Test
public void testAdvice() throws Exception {
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setQueueNames(Q1, Q2);/*from  ww w  .  j av  a 2s .  c o  m*/
    container.setConsumersPerQueue(2);
    final CountDownLatch latch = new CountDownLatch(2);
    container.setMessageListener(m -> latch.countDown());
    final CountDownLatch adviceLatch = new CountDownLatch(2);
    MethodInterceptor advice = i -> {
        adviceLatch.countDown();
        return i.proceed();
    };
    container.setAdviceChain(advice);
    container.setBeanName("advice");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    RabbitTemplate template = new RabbitTemplate(cf);
    template.convertAndSend(Q1, "foo");
    template.convertAndSend(Q1, "bar");
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertTrue(adviceLatch.await(10, TimeUnit.SECONDS));
    container.stop();
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size());
    cf.destroy();
}

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

@Test
public void testQueueManagement() throws Exception {
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setThreadNamePrefix("client-");
    executor.afterPropertiesSet();//  w  w w.jav a  2 s  .  c  om
    cf.setExecutor(executor);
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setConsumersPerQueue(2);
    container.setMessageListener(new MessageListenerAdapter((ReplyingMessageListener<String, String>) in -> {
        if ("foo".equals(in) || "bar".equals(in)) {
            return in.toUpperCase();
        } else {
            return null;
        }
    }));
    container.setBeanName("qManage");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    container.addQueueNames(Q1, Q2);
    assertTrue(consumersOnQueue(Q1, 2));
    assertTrue(consumersOnQueue(Q2, 2));
    RabbitTemplate template = new RabbitTemplate(cf);
    assertEquals("FOO", template.convertSendAndReceive(Q1, "foo"));
    assertEquals("BAR", template.convertSendAndReceive(Q2, "bar"));
    container.removeQueueNames(Q1, Q2, "junk");
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    container.stop();
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size());
    template.stop();
    cf.destroy();
}