Example usage for com.rabbitmq.client Connection createChannel

List of usage examples for com.rabbitmq.client Connection createChannel

Introduction

In this page you can find the example usage for com.rabbitmq.client Connection createChannel.

Prototype

Channel createChannel(int channelNumber) throws IOException;

Source Link

Document

Create a new channel, using the specified channel number if possible.

Usage

From source file:org.apache.synapse.transport.amqp.connectionfactory.AMQPTransportConnectionFactory.java

License:Apache License

private Channel createChannel(Connection connection, Map<String, String> parameters) throws IOException {
    Channel ch;//from  ww w .  ja v a2s . c o  m
    if (parameters.get(AMQPTransportConstant.PARAMETER_AMQP_CHANNEL_NUMBER) != null) {
        int index = 0;
        try {
            index = Integer.parseInt(parameters.get(AMQPTransportConstant.PARAMETER_AMQP_CHANNEL_NUMBER));
        } catch (NumberFormatException e) {
            index = 1; // assume default,
            // fair dispatch see http://www.rabbitmq.com/tutorials/tutorial-two-java.html
        }
        ch = connection.createChannel(index);

    } else {
        ch = connection.createChannel();
    }

    int prefetchSize = 1024;
    if (parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_PREFETCH_SIZE) != null) {
        try {
            prefetchSize = Integer
                    .parseInt(parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_PREFETCH_SIZE));
        } catch (NumberFormatException e) {
            prefetchSize = 1024; // assume default
        }
    }

    int prefetchCount = 0;
    if (parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_PREFETCH_COUNT) != null) {
        try {
            prefetchCount = Integer
                    .parseInt(parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_PREFETCH_COUNT));
            ch.basicQos(prefetchCount);
        } catch (NumberFormatException e) {
            prefetchCount = 0; // assume default
        }
    }

    boolean useGlobally = false;
    if (parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_QOS_GLOBAL) != null) {
        useGlobally = Boolean.parseBoolean(parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_QOS_GLOBAL));
    }
    return ch;
}

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

License:Apache License

@Test
public void testChannelCache() throws Exception {
    Connection c1 = this.channelCf.createConnection();
    Connection c2 = this.channelCf.createConnection();
    assertSame(c1, c2);/*from  w  w w.j  ava  2  s. c o  m*/
    Channel ch1 = c1.createChannel(false);
    Channel ch2 = c1.createChannel(false);
    Channel ch3 = c1.createChannel(true);
    Channel ch4 = c1.createChannel(true);
    Channel ch5 = c1.createChannel(true);
    ch1.close();
    ch2.close();
    ch3.close();
    ch4.close();
    ch5.close();
    Properties props = this.channelCf.getCacheProperties();
    assertEquals("4", props.getProperty("channelCacheSize"));
    assertEquals("2", props.getProperty("idleChannelsNotTx"));
    assertEquals("3", props.getProperty("idleChannelsTx"));
    assertEquals("2", props.getProperty("idleChannelsNotTxHighWater"));
    assertEquals("3", props.getProperty("idleChannelsTxHighWater"));
    ch1 = c1.createChannel(false);
    ch3 = c1.createChannel(true);
    props = this.channelCf.getCacheProperties();
    assertEquals("1", props.getProperty("idleChannelsNotTx"));
    assertEquals("2", props.getProperty("idleChannelsTx"));
    assertEquals("2", props.getProperty("idleChannelsNotTxHighWater"));
    assertEquals("3", props.getProperty("idleChannelsTxHighWater"));
    ch1 = c1.createChannel(false);
    ch2 = c1.createChannel(false);
    ch3 = c1.createChannel(true);
    ch4 = c1.createChannel(true);
    ch5 = c1.createChannel(true);
    Channel ch6 = c1.createChannel(true);
    Channel ch7 = c1.createChannel(true); // #5
    ch1.close();
    ch2.close();
    ch3.close();
    ch4.close();
    ch5.close();
    ch6.close();
    ch7.close();
    props = this.channelCf.getCacheProperties();
    assertEquals("2", props.getProperty("idleChannelsNotTx"));
    assertEquals("4", props.getProperty("idleChannelsTx")); // not 5
    assertEquals("2", props.getProperty("idleChannelsNotTxHighWater"));
    assertEquals("4", props.getProperty("idleChannelsTxHighWater")); // not 5

}

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

License:Apache License

@Test
public void testConnectionCache() throws Exception {
    Connection c1 = this.connectionCf.createConnection();
    Connection c2 = this.connectionCf.createConnection();
    Channel ch1 = c1.createChannel(false);
    Channel ch2 = c1.createChannel(false);
    Channel ch3 = c2.createChannel(true);
    Channel ch4 = c2.createChannel(true);
    Channel ch5 = c2.createChannel(false);
    ch1.close();/*from   w w  w . j a  v  a  2s .c om*/
    ch2.close();
    ch3.close();
    ch4.close();
    ch5.close();
    c1.close();
    Properties props = this.connectionCf.getCacheProperties();
    assertEquals("10", props.getProperty("channelCacheSize"));
    assertEquals("5", props.getProperty("connectionCacheSize"));
    assertEquals("2", props.getProperty("openConnections"));
    assertEquals("1", props.getProperty("idleConnections"));
    c2.close();
    props = this.connectionCf.getCacheProperties();
    assertEquals("2", props.getProperty("idleConnections"));
    assertEquals("2", props.getProperty("idleConnectionsHighWater"));
    int c1Port = c1.getLocalPort();
    int c2Port = c2.getLocalPort();
    assertEquals("2", props.getProperty("idleChannelsNotTx:" + c1Port));
    assertEquals("0", props.getProperty("idleChannelsTx:" + c1Port));
    assertEquals("2", props.getProperty("idleChannelsNotTxHighWater:" + c1Port));
    assertEquals("0", props.getProperty("idleChannelsTxHighWater:" + c1Port));
    assertEquals("1", props.getProperty("idleChannelsNotTx:" + c2Port));
    assertEquals("2", props.getProperty("idleChannelsTx:" + c2Port));
    assertEquals("1", props.getProperty("idleChannelsNotTxHighWater:" + c2Port));
    assertEquals("2", props.getProperty("idleChannelsTxHighWater:" + c2Port));
}

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

License:Apache License

@Test
public void testCachedConnectionsAndChannels() throws Exception {
    connectionFactory.setCacheMode(CacheMode.CONNECTION);
    connectionFactory.setConnectionCacheSize(1);
    connectionFactory.setChannelCacheSize(3);
    List<Connection> connections = new ArrayList<Connection>();
    connections.add(connectionFactory.createConnection());
    connections.add(connectionFactory.createConnection());
    Set<?> openConnections = TestUtils.getPropertyValue(connectionFactory, "openConnections", Set.class);
    assertEquals(2, openConnections.size());
    assertNotSame(connections.get(0), connections.get(1));
    List<Channel> channels = new ArrayList<Channel>();
    for (int i = 0; i < 5; i++) {
        channels.add(connections.get(0).createChannel(false));
        channels.add(connections.get(1).createChannel(false));
        channels.add(connections.get(0).createChannel(true));
        channels.add(connections.get(1).createChannel(true));
    }/*from   w  w w  .  j  a  v  a  2 s .  c  om*/
    @SuppressWarnings("unchecked")
    Map<?, List<?>> cachedChannels = TestUtils.getPropertyValue(connectionFactory,
            "openConnectionNonTransactionalChannels", Map.class);
    assertEquals(0, cachedChannels.get(connections.get(0)).size());
    assertEquals(0, cachedChannels.get(connections.get(1)).size());
    @SuppressWarnings("unchecked")
    Map<?, List<?>> cachedTxChannels = TestUtils.getPropertyValue(connectionFactory,
            "openConnectionTransactionalChannels", Map.class);
    assertEquals(0, cachedTxChannels.get(connections.get(0)).size());
    assertEquals(0, cachedTxChannels.get(connections.get(1)).size());
    for (Channel channel : channels) {
        channel.close();
    }
    assertEquals(3, cachedChannels.get(connections.get(0)).size());
    assertEquals(3, cachedChannels.get(connections.get(1)).size());
    assertEquals(3, cachedTxChannels.get(connections.get(0)).size());
    assertEquals(3, cachedTxChannels.get(connections.get(1)).size());
    for (int i = 0; i < 3; i++) {
        assertEquals(channels.get(i * 4), connections.get(0).createChannel(false));
        assertEquals(channels.get(i * 4 + 1), connections.get(1).createChannel(false));
        assertEquals(channels.get(i * 4 + 2), connections.get(0).createChannel(true));
        assertEquals(channels.get(i * 4 + 3), connections.get(1).createChannel(true));
    }
    assertEquals(0, cachedChannels.get(connections.get(0)).size());
    assertEquals(0, cachedChannels.get(connections.get(1)).size());
    assertEquals(0, cachedTxChannels.get(connections.get(0)).size());
    assertEquals(0, cachedTxChannels.get(connections.get(1)).size());
    for (Channel channel : channels) {
        channel.close();
    }
    for (Connection connection : connections) {
        connection.close();
    }
    assertEquals(3, cachedChannels.get(connections.get(0)).size());
    assertNull(cachedChannels.get(connections.get(1)));
    assertEquals(3, cachedTxChannels.get(connections.get(0)).size());
    assertNull(cachedTxChannels.get(connections.get(1)));

    assertEquals(1, openConnections.size());

    Connection connection = connectionFactory.createConnection();
    Connection rabbitConnection = TestUtils.getPropertyValue(connection, "target", Connection.class);
    rabbitConnection.close();
    Channel channel = connection.createChannel(false);
    assertEquals(1, openConnections.size());
    channel.close();
    connection.close();
    assertEquals(1, openConnections.size());
}

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

License:Apache License

@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  .  ja  v a2s . 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((ExecutorService) null);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setCacheMode(CacheMode.CONNECTION);
    ccf.afterPropertiesSet();

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

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

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

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

    Connection con1 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con1);
    assertEquals(1, openConnections.size());
    assertEquals(0, idleConnections.size());
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(0), targetDelegate(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, openConnections.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, openConnections.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, openConnections.size());
    assertEquals(0, idleConnections.size());
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(1), targetDelegate(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, openConnections.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, openConnections.size());
    assertEquals(0, idleConnections.size());

    channel2.close();
    con2.close();
    assertEquals(2, openConnections.size());
    assertEquals(1, idleConnections.size());
    channel3.close();
    con3.close();
    assertEquals(1, openConnections.size());
    assertEquals(1, idleConnections.size());
    /*
     *  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), targetDelegate(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);
    con3 = ccf.createConnection();
    assertNotNull(closedNotification.get());
    assertSame(mockConnections.get(1), targetDelegate(closedNotification.getAndSet(null)));
    verifyConnectionIs(mockConnections.get(2), con3);
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(2), targetDelegate(createNotification.getAndSet(null)));
    assertEquals(1, openConnections.size());
    assertEquals(0, idleConnections.size());
    channel3 = con3.createChannel(false);
    verifyChannelIs(mockChannels.get(2), channel3);
    channel3.close();
    con3.close();
    assertNull(closedNotification.get());
    assertEquals(1, openConnections.size());
    assertEquals(1, idleConnections.size());

    /*
     * Now a closed cached connection when creating a channel
     */
    con3 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(2), con3);
    assertNull(createNotification.get());
    assertEquals(1, openConnections.size());
    assertEquals(0, 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(1, openConnections.size());
    assertEquals(1, idleConnections.size());

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

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

License:Apache License

@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. ja  v 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((ExecutorService) null);

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

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

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

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

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

    Connection con1 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con1);
    assertEquals(1, openConnections.size());
    assertEquals(0, idleConnections.size());
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(0), targetDelegate(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, openConnections.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, openConnections.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, openConnections.size());
    assertEquals(0, idleConnections.size());
    assertNotNull(createNotification.get());
    assertSame(mockConnections.get(1), targetDelegate(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, openConnections.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, openConnections.size());
    assertEquals(0, idleConnections.size());

    channel2.close();
    con2.close();
    assertEquals(2, openConnections.size());
    assertEquals(1, idleConnections.size());
    channel3.close();
    con3.close();
    assertEquals(2, openConnections.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), targetDelegate(closedNotification.getAndSet(null)));
    verifyConnectionIs(mockConnections.get(0), con3);
    assertNull(createNotification.get());
    assertEquals(1, openConnections.size());
    assertEquals(0, idleConnections.size());
    channel3 = con3.createChannel(false);
    verifyChannelIs(mockChannels.get(0), channel3);
    channel3.close();
    con3.close();
    assertNull(closedNotification.get());
    assertEquals(1, openConnections.size());
    assertEquals(1, idleConnections.size());

    /*
     * Now a closed cached connection when creating a channel
     */
    con3 = ccf.createConnection();
    verifyConnectionIs(mockConnections.get(0), con3);
    assertNull(createNotification.get());
    assertEquals(1, openConnections.size());
    assertEquals(0, 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(1, openConnections.size());
    assertEquals(1, idleConnections.size());

    Connection con4 = ccf.createConnection();
    assertSame(con3, con4);
    assertEquals(0, 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), never()).close(30000);
    verify(mockConnections.get(1), never()).close(30000);
    verify(mockConnections.get(2)).close(30000);
}

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

License:Apache License

/**
 * Obtain a RabbitMQ Channel that is synchronized with the current transaction, if any.
 * @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
 *//*from   w w  w .ja  va2s.c  o  m*/
public static RabbitResourceHolder getTransactionalResourceHolder(final ConnectionFactory connectionFactory,
        final boolean synchedLocalTransactionAllowed) {

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

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

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

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

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

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

License:Apache License

@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 -> {//w  w w. j  a  va2 s.co  m
        String tag = UUID.randomUUID().toString();
        consumers.put(address, invocation.getArgumentAt(6, Consumer.class));
        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.connection.RoutingConnectionFactoryTests.java

License:Apache License

@Test
public void testWithSMLCAndConnectionListener() throws Exception {
    ConnectionFactory connectionFactory1 = mock(ConnectionFactory.class);
    Map<Object, ConnectionFactory> factories = new HashMap<Object, ConnectionFactory>(2);
    factories.put("xxx[foo]", connectionFactory1);

    final SimpleRoutingConnectionFactory connectionFactory = new SimpleRoutingConnectionFactory();

    final Connection connection = mock(Connection.class);
    Channel channel = mock(Channel.class);
    given(connection.createChannel(anyBoolean())).willReturn(channel);
    final AtomicReference<Object> connectionMakerKey1 = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    willAnswer(i -> {//from www  .j a v  a2s.  c  om
        connectionMakerKey1.set(connectionFactory.determineCurrentLookupKey());
        latch.countDown();
        return connection;
    }).given(connectionFactory1).createConnection();
    connectionFactory.setTargetConnectionFactories(factories);

    final AtomicReference<Object> connectionMakerKey2 = new AtomicReference<>();
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory) {

        @Override
        protected synchronized void redeclareElementsIfNecessary() {
            connectionMakerKey2.set(connectionFactory.determineCurrentLookupKey());
        }

    };
    container.setQueueNames("foo");
    container.setLookupKeyQualifier("xxx");
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    container.stop();
    assertThat(connectionMakerKey1.get(), equalTo("xxx[foo]"));
    assertThat(connectionMakerKey2.get(), equalTo("xxx[foo]"));
}

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

License:Apache License

@Test
public void testWithDMLCAndConnectionListener() throws Exception {
    ConnectionFactory connectionFactory1 = mock(ConnectionFactory.class);
    Map<Object, ConnectionFactory> factories = new HashMap<Object, ConnectionFactory>(2);
    factories.put("xxx[foo]", connectionFactory1);

    final SimpleRoutingConnectionFactory connectionFactory = new SimpleRoutingConnectionFactory();

    final Connection connection = mock(Connection.class);
    Channel channel = mock(Channel.class);
    given(connection.createChannel(anyBoolean())).willReturn(channel);
    final AtomicReference<Object> connectionMakerKey = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    willAnswer(i -> {//from ww  w.j  a v a 2s. c  om
        connectionMakerKey.set(connectionFactory.determineCurrentLookupKey());
        latch.countDown();
        return connection;
    }).given(connectionFactory1).createConnection();
    connectionFactory.setTargetConnectionFactories(factories);

    final AtomicReference<Object> connectionMakerKey2 = new AtomicReference<>();
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(connectionFactory) {

        @Override
        protected synchronized void redeclareElementsIfNecessary() {
            connectionMakerKey2.set(connectionFactory.determineCurrentLookupKey());
        }

    };
    container.setQueueNames("foo");
    container.setLookupKeyQualifier("xxx");
    container.setShutdownTimeout(10);
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    container.stop();
    assertThat(connectionMakerKey.get(), equalTo("xxx[foo]"));
    assertThat(connectionMakerKey2.get(), equalTo("xxx[foo]"));
}