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

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

Introduction

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

Prototype

public void setChannelCacheSize(int sessionCacheSize) 

Source Link

Document

The number of channels to maintain in the cache.

Usage

From source file:com.xoom.rabbit.test.Main.java

public static void main(String[] args) throws InterruptedException {
    if (args.length != 9) {
        System.out.println(//from  ww w  .j  av a  2  s. c  o  m
                "usage: java -jar target/rabbit-tester-0.1-SNAPSHOT-standalone.jar [consumer_threads] [number_of_messages] [amqp_host] [amqp_port] [produce] [consume] [message size in bytes] [username] [password]");
        return;
    }
    final long startTime = System.currentTimeMillis();
    int consumerThreads = Integer.parseInt(args[0]);
    final int messages = Integer.parseInt(args[1]);
    String host = args[2];
    int port = Integer.parseInt(args[3]);
    boolean produce = Boolean.parseBoolean(args[4]);
    boolean consume = Boolean.parseBoolean(args[5]);
    final int messageSize = Integer.parseInt(args[6]);
    String username = args[7];
    String password = args[8];

    if (produce) {
        System.out.println("Sending " + messages + " messages to " + host + ":" + port);
    }
    if (consume) {
        System.out.println("Consuming " + messages + " messages from " + host + ":" + port);
    }
    if (!produce && !consume) {
        System.out.println("Not producing or consuming any messages.");
    }

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setChannelCacheSize(consumerThreads + 1);

    RabbitAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

    DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false);
    Queue queue = new Queue(QUEUE_NAME);
    amqpAdmin.declareExchange(exchange);
    amqpAdmin.declareQueue(queue);
    amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY));

    final AmqpTemplate amqpTemplate = new RabbitTemplate(connectionFactory);

    final CountDownLatch producerLatch = new CountDownLatch(messages);
    final CountDownLatch consumerLatch = new CountDownLatch(messages);

    SimpleMessageListenerContainer listenerContainer = null;

    if (consume) {
        listenerContainer = new SimpleMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setQueueNames(QUEUE_NAME);
        listenerContainer.setConcurrentConsumers(consumerThreads);
        listenerContainer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (consumerLatch.getCount() == 1) {
                    System.out.println("Finished consuming " + messages + " messages in "
                            + (System.currentTimeMillis() - startTime) + "ms");
                }
                consumerLatch.countDown();
            }
        });
        listenerContainer.start();
    }

    if (produce) {
        while (producerLatch.getCount() > 0) {
            try {
                byte[] message = new byte[messageSize];
                RND.nextBytes(message);
                amqpTemplate.send(EXCHANGE_NAME, ROUTING_KEY, new Message(message, new MessageProperties()));
                producerLatch.countDown();
            } catch (Exception e) {
                System.out.println("Failed to send message " + (messages - producerLatch.getCount())
                        + " will retry forever.");
            }
        }
    }

    if (consume) {
        consumerLatch.await();
        listenerContainer.shutdown();
    }

    connectionFactory.destroy();
}

From source file:acromusashi.stream.component.rabbitmq.AmqpTemplateFactoryTest.java

/**
 * ???//from w  ww.  j a va2s.c o  m
 * 
 * @target {@link AmqpTemplateFactory#getAmqpTemplate(String)}
 * @test ???(??null:)
 *    condition:: ??:null
 *    result:: ????
 * 
 * @test ???(??null:)
 *    condition:: ??:null
 *    result:: ??????
 * 
 * @test ???(??:)
 *    condition:: ??:
 *    result:: ????
 * 
 * @test ???(??:)
 *    condition:: ??:
 *    result:: ??????
 * 
 * @test ???(????:??)
 *    condition:: ??:????
 *    result:: ??????
 * 
 * @test ???(????:ConnectionFactory?)
 *    condition:: ??:????
 *    result:: ??ConnectionFactory??????
 * 
 * @test ???(????:?)
 *    condition:: ??:????
 *    result:: 2???1?????????
 * 
 * @test ???(???????:)
 *    condition:: ??:???????
 *    result:: ????
 * 
 * @test ???(???????:)
 *    condition:: ??:???????
 *    result:: ??????
 */
@DataPoints
public static Fixture[] createFixture_QueueName() {
    List<Fixture> patterns = new ArrayList<Fixture>();

    // null
    patterns.add(new Fixture(null, new RabbitmqCommunicateException("QueueName is not defined.")));

    // 
    patterns.add(new Fixture("",
            new RabbitmqCommunicateException("QueueNames ProcessList is not defined. QueueName={0}")));

    // ????
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setChannelCacheSize(10);
    patterns.add(new Fixture(DEFINED_QUEUE_NAME, new RabbitTemplate(connectionFactory)));

    // ???????
    patterns.add(new Fixture(NON_DEFINED_QUEUE_NAME,
            new RabbitmqCommunicateException("QueueNames ProcessList is not defined. QueueName={0}")));

    return patterns.toArray(new Fixture[patterns.size()]);
}

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

@Test
public void testWithConnectionFactoryCacheSize() throws Exception {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);
    Channel mockTxChannel = mock(Channel.class);

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

    when(mockChannel1.basicGet("foo", false)).thenReturn(new GetResponse(null, null, null, 1));
    when(mockChannel2.basicGet("bar", false)).thenReturn(new GetResponse(null, null, null, 1));
    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setExecutor(mock(ExecutorService.class));
    ccf.setChannelCacheSize(2);

    Connection con = ccf.createConnection();

    Channel channel1 = con.createChannel(false);
    Channel channel2 = con.createChannel(false);

    ChannelProxy txChannel = (ChannelProxy) con.createChannel(true);
    assertTrue(txChannel.isTransactional());
    verify(mockTxChannel).txSelect();/*from   w w w  .  j av a2s .c o  m*/
    txChannel.close();

    channel1.basicGet("foo", true);
    channel2.basicGet("bar", true);

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

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

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

    ch1.close();
    ch2.close();

    verify(mockConnection, times(3)).createChannel();

    con.close(); // should be ignored

    verify(mockConnection, never()).close();
    verify(mockChannel1, never()).close();
    verify(mockChannel2, never()).close();

}

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

@Test
public void testCacheSizeExceeded() throws Exception {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);
    Channel mockChannel3 = mock(Channel.class);

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection);
    when(mockConnection.createChannel()).thenReturn(mockChannel1).thenReturn(mockChannel2)
            .thenReturn(mockChannel3);/*from w w w. j  a v a  2s .  c o m*/
    when(mockConnection.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(1);

    Connection con = ccf.createConnection();

    Channel channel1 = con.createChannel(false);
    // cache size is 1, but the other connection is not released yet so this
    // creates a new one
    Channel channel2 = con.createChannel(false);
    assertNotSame(channel1, channel2);

    // should be ignored, and added last into channel cache.
    channel1.close();
    // should be physically closed
    channel2.close();

    // remove first entry in cache (channel1)
    Channel ch1 = con.createChannel(false);
    // create a new channel
    Channel ch2 = con.createChannel(false);

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

    ch1.close();
    ch2.close();

    verify(mockConnection, times(3)).createChannel();

    con.close(); // should be ignored

    verify(mockConnection, never()).close();
    verify(mockChannel1, never()).close();
    verify(mockChannel2, atLeastOnce()).close();
    verify(mockChannel3, atLeastOnce()).close();

}

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

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

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

    // Called during physical close
    when(mockChannel1.isOpen()).thenReturn(true);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setExecutor(mock(ExecutorService.class));
    ccf.setChannelCacheSize(1);
    ccf.setChannelCheckoutTimeout(10);/*from  w w w .  j a v a 2s.  c om*/

    Connection con = ccf.createConnection();

    Channel channel1 = con.createChannel(false);

    try {
        con.createChannel(false);
        fail("Exception expected");
    } catch (AmqpTimeoutException e) {
    }

    // should be ignored, and added last into channel cache.
    channel1.close();

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

    assertSame(ch1, channel1);

    ch1.close();

    verify(mockConnection, times(1)).createChannel();

    con.close(); // should be ignored

    verify(mockConnection, never()).close();
    verify(mockChannel1, never()).close();

    ccf.destroy();
}

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

@Test
public void testCheckoutLimitWithFailures() throws Exception {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    final com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    final AtomicBoolean brokerDown = new AtomicBoolean();

    willAnswer(i -> {// w  ww .j a v  a2s .co m
        if (brokerDown.get()) {
            throw new AmqpConnectException(null);
        }
        return mockConnection;
    }).given(mockConnectionFactory).newConnection((ExecutorService) isNull(), anyString());

    when(mockConnection.createChannel()).thenReturn(mockChannel1);

    doAnswer(i -> !brokerDown.get()).when(mockConnection).isOpen();

    // Called during physical close
    doAnswer(i -> !brokerDown.get()).when(mockChannel1).isOpen();

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setChannelCacheSize(1);
    ccf.setChannelCheckoutTimeout(10);

    Connection con = ccf.createConnection();

    Channel channel1 = con.createChannel(false);

    try {
        con.createChannel(false);
        fail("Exception expected");
    } catch (AmqpTimeoutException e) {
    }

    // should be ignored, and added last into channel cache.
    channel1.close();

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

    assertSame(ch1, channel1);

    ch1.close();

    brokerDown.set(true);
    try {
        con.createChannel(false);
        fail("Exception expected");
    } catch (AmqpConnectException e) {
    }
    brokerDown.set(false);
    ch1 = con.createChannel(false);
    ch1.close();

    ccf.destroy();
}

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

private void testCheckoutsWithRefreshedConnectionGuts(CacheMode mode) 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);
    Channel mockChannel4 = mock(Channel.class);

    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, mockChannel4);
    when(mockConnection2.isOpen()).thenReturn(true);

    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);
    when(mockChannel3.isOpen()).thenReturn(true);
    when(mockChannel4.isOpen()).thenReturn(true);

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

    ccf.addConnectionListener(connection -> {
        try {
            // simulate admin
            connection.createChannel(false).close();
        } catch (Exception e) {
            fail(e.getMessage());
        }
    });

    Connection con = ccf.createConnection();

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

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

    when(mockConnection1.isOpen()).thenReturn(false);
    when(mockChannel1.isOpen()).thenReturn(false);
    when(mockChannel2.isOpen()).thenReturn(false);

    con.createChannel(false).close();
    con = ccf.createConnection();
    con.createChannel(false).close();
    con.createChannel(false).close();
    con.createChannel(false).close();
    con.createChannel(false).close();
    con.createChannel(false).close();

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

    con.close();

    verify(mockConnection2, never()).close();

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

    ccf.destroy();

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

}

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

@Test
public void testCheckoutLimitWithRelease() throws IOException, Exception {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel1 = mock(Channel.class);

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

    // Called during physical close
    when(mockChannel1.isOpen()).thenReturn(true);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setExecutor(mock(ExecutorService.class));
    ccf.setChannelCacheSize(1);
    ccf.setChannelCheckoutTimeout(10000);

    final Connection con = ccf.createConnection();

    final AtomicReference<Channel> channelOne = new AtomicReference<Channel>();
    final CountDownLatch latch = new CountDownLatch(1);

    new Thread(() -> {
        Channel channel1 = con.createChannel(false);
        latch.countDown();//from  w  w w.  j  a  va 2  s.  c  o  m
        channelOne.set(channel1);
        try {
            Thread.sleep(100);
            channel1.close();
        } catch (InterruptedException e1) {
            Thread.currentThread().interrupt();
        } catch (IOException e2) {
        } catch (TimeoutException e3) {
        }
    }).start();

    assertTrue(latch.await(10, TimeUnit.SECONDS));
    Channel channel2 = con.createChannel(false);
    assertSame(channelOne.get(), channel2);

    channel2.close();

    verify(mockConnection, never()).close();
    verify(mockChannel1, never()).close();

    ccf.destroy();
}

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

@Test
public void testReleaseWithForcedPhysicalClose() 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);
    ccf.setChannelCheckoutTimeout(10);//w  w w.  j  a v a2  s .  co  m

    Connection con = ccf.createConnection();

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

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

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

    channel1.close();
    RabbitUtils.setPhysicalCloseRequired(channel1, false);
    con.close();
    verify(mockChannel1).close();
    verify(mockConnection1, never()).close();

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

    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 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);
    ccf.setChannelCheckoutTimeout(10);/* w ww. ja v  a  2  s  . c om*/

    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());

}