Example usage for org.springframework.amqp.rabbit.connection ConnectionFactory createConnection

List of usage examples for org.springframework.amqp.rabbit.connection ConnectionFactory createConnection

Introduction

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

Prototype

Connection createConnection() throws AmqpException;

Source Link

Usage

From source file:com.gopivotal.cloudfoundry.test.core.RabbitUtils.java

public String checkAccess(ConnectionFactory connectionFactory) {
    try {//from ww w  .  j a v a 2  s. co m
        connectionFactory.createConnection();
        return "ok";
    } catch (Exception e) {
        return "failed with " + e.getMessage();
    }
}

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

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

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

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

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

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

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

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

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

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

@Test
public void testContainerNotRecoveredAfterExhaustingRecoveryBackOff() throws Exception {
    ConnectionFactory mockCF = mock(ConnectionFactory.class);
    given(mockCF.createConnection()).willThrow(new RuntimeException("intended - backOff test"));
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(mockCF);
    container.setQueueNames("foo");
    container.setRecoveryBackOff(new FixedBackOff(100, 3));
    container.setMissingQueuesFatal(false);
    container.setBeanName("backOff");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();/*from w  ww .  j a v a2  s  .com*/
    container.start();

    // Since backOff exhausting makes listenerContainer as invalid (calls stop()),
    // it is enough to check the listenerContainer activity
    int n = 0;
    while (container.isActive() && n++ < 100) {
        Thread.sleep(100);
    }
    assertFalse(container.isActive());
}

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

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

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

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

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

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

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

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

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

@Test
public void testRestartConsumerOnBasicQosIoException() throws Exception {
    this.template.convertAndSend(queue.getName(), "foo");

    ConnectionFactory connectionFactory = new SingleConnectionFactory("localhost", BrokerTestUtils.getPort());

    final AtomicBoolean networkGlitch = new AtomicBoolean();

    class MockChannel extends PublisherCallbackChannelImpl {

        MockChannel(Channel delegate) {
            super(delegate);
        }// www  .j  av a 2s . co m

        @Override
        public void basicQos(int prefetchCount) throws IOException {
            if (networkGlitch.compareAndSet(false, true)) {
                throw new IOException("Intentional connection reset");
            }
            super.basicQos(prefetchCount);
        }

    }

    Connection connection = spy(connectionFactory.createConnection());
    when(connection.createChannel(anyBoolean()))
            .then(invocation -> new MockChannel((Channel) invocation.callRealMethod()));

    DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
    dfa.setPropertyValue("connection", connection);

    CountDownLatch latch = new CountDownLatch(1);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch)));
    container.setQueueNames(queue.getName());
    container.setRecoveryInterval(500);
    container.afterPropertiesSet();
    container.start();

    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertTrue(networkGlitch.get());

    container.stop();
    ((DisposableBean) connectionFactory).destroy();
}

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

@Test
public void testRestartConsumerOnConnectionLossDuringQueueDeclare() throws Exception {
    this.template.convertAndSend(queue.getName(), "foo");

    ConnectionFactory connectionFactory = new CachingConnectionFactory("localhost", BrokerTestUtils.getPort());

    final AtomicBoolean networkGlitch = new AtomicBoolean();

    class MockChannel extends PublisherCallbackChannelImpl {

        MockChannel(Channel delegate) {
            super(delegate);
        }//from   w  w w  .ja v  a 2  s . c  o m

        @Override
        public DeclareOk queueDeclarePassive(String queue) throws IOException {
            if (networkGlitch.compareAndSet(false, true)) {
                getConnection().close();
                throw new IOException("Intentional connection reset");
            }
            return super.queueDeclarePassive(queue);
        }

    }

    Connection connection = spy(connectionFactory.createConnection());
    when(connection.createChannel(anyBoolean()))
            .then(invocation -> new MockChannel((Channel) invocation.callRealMethod()));

    DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
    dfa.setPropertyValue("connection", connection);

    CountDownLatch latch = new CountDownLatch(1);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch)));
    container.setQueueNames(queue.getName());
    container.setRecoveryInterval(500);
    container.afterPropertiesSet();
    container.start();

    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertTrue(networkGlitch.get());

    container.stop();
    ((DisposableBean) connectionFactory).destroy();
}