Example usage for org.springframework.amqp.rabbit.core RabbitTemplate RabbitTemplate

List of usage examples for org.springframework.amqp.rabbit.core RabbitTemplate RabbitTemplate

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.core RabbitTemplate RabbitTemplate.

Prototype

public RabbitTemplate(ConnectionFactory connectionFactory) 

Source Link

Document

Create a rabbit template with default strategies and settings.

Usage

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

@Test
public void testSendAndReceiveTransactedWithUncachedConnection() throws Exception {
    RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory());
    template.setChannelTransacted(true);
    template.convertAndSend(ROUTE, "message");
    String result = (String) template.receiveAndConvert(ROUTE);
    assertEquals("message", result);
    result = (String) template.receiveAndConvert(ROUTE);
    assertEquals(null, result);/*from  w  w w. j  av a 2  s  .  co  m*/
}

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

@Test
public void testAtomicSendAndReceive() throws Exception {
    final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory());
    template.setRoutingKey(ROUTE);//w  ww  .j a  v a2  s.  co  m
    template.setQueue(ROUTE);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;
            for (int i = 0; i < 10; i++) {
                message = template.receive();
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive(message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive();
    assertEquals(null, reply);
}

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

@Test
public void testAtomicSendAndReceiveExternalExecutor() throws Exception {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
    final String execName = "make-sure-exec-passed-in";
    exec.setBeanName(execName);//www .j a  v  a  2  s .  c  o m
    exec.afterPropertiesSet();
    connectionFactory.setExecutor(exec);
    final Field[] fields = new Field[1];
    ReflectionUtils.doWithFields(RabbitTemplate.class, new FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            field.setAccessible(true);
            fields[0] = field;
        }
    }, new FieldFilter() {
        public boolean matches(Field field) {
            return field.getName().equals("logger");
        }
    });
    Log logger = Mockito.mock(Log.class);
    when(logger.isTraceEnabled()).thenReturn(true);

    final AtomicBoolean execConfiguredOk = new AtomicBoolean();

    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            String log = (String) invocation.getArguments()[0];
            if (log.startsWith("Message received") && Thread.currentThread().getName().startsWith(execName)) {
                execConfiguredOk.set(true);
            }
            return null;
        }
    }).when(logger).trace(Mockito.anyString());
    final RabbitTemplate template = new RabbitTemplate(connectionFactory);
    ReflectionUtils.setField(fields[0], template, logger);
    template.setRoutingKey(ROUTE);
    template.setQueue(ROUTE);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;
            for (int i = 0; i < 10; i++) {
                message = template.receive();
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive(message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive();
    assertEquals(null, reply);

    assertTrue(execConfiguredOk.get());
}

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

@Test
public void testAtomicSendAndReceiveWithRoutingKey() throws Exception {
    final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory());
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;// w  w  w  . ja v  a  2 s  .c o m
            for (int i = 0; i < 10; i++) {
                message = template.receive(ROUTE);
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive(ROUTE, message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive(ROUTE);
    assertEquals(null, reply);
}

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

@Test
public void testAtomicSendAndReceiveWithExchangeAndRoutingKey() throws Exception {
    final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory());
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;//from  w w w . ja va2 s .  c  o  m
            for (int i = 0; i < 10; i++) {
                message = template.receive(ROUTE);
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive("", ROUTE, message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive(ROUTE);
    assertEquals(null, reply);
}

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

@Test
public void testAtomicSendAndReceiveWithConversion() throws Exception {
    final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory());
    template.setRoutingKey(ROUTE);//from  ww w  .  j a v  a 2  s .  com
    template.setQueue(ROUTE);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<String> received = executor.submit(new Callable<String>() {

        public String call() throws Exception {
            Message message = null;
            for (int i = 0; i < 10; i++) {
                message = template.receive();
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return (String) template.getMessageConverter().fromMessage(message);
        }

    });
    String result = (String) template.convertSendAndReceive("message");
    assertEquals("message", received.get(1000, TimeUnit.MILLISECONDS));
    assertEquals("message", result);
    // Message was consumed so nothing left on queue
    result = (String) template.receiveAndConvert();
    assertEquals(null, result);
}

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

@Test
public void testAtomicSendAndReceiveWithConversionAndMessagePostProcessor() throws Exception {
    final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory());
    template.setRoutingKey(ROUTE);//from ww w. ja va 2 s  .c o  m
    template.setQueue(ROUTE);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<String> received = executor.submit(new Callable<String>() {

        public String call() throws Exception {
            Message message = null;
            for (int i = 0; i < 10; i++) {
                message = template.receive();
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return (String) template.getMessageConverter().fromMessage(message);
        }

    });
    String result = (String) template.convertSendAndReceive((Object) "message", new MessagePostProcessor() {
        public Message postProcessMessage(Message message) throws AmqpException {
            try {
                byte[] newBody = new String(message.getBody(), "UTF-8").toUpperCase().getBytes("UTF-8");
                return new Message(newBody, message.getMessageProperties());
            } catch (Exception e) {
                throw new AmqpException("unexpected failure in test", e);
            }
        }
    });
    assertEquals("MESSAGE", received.get(1000, TimeUnit.MILLISECONDS));
    assertEquals("MESSAGE", result);
    // Message was consumed so nothing left on queue
    result = (String) template.receiveAndConvert();
    assertEquals(null, result);
}

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

@Before
public void create() {
    connectionFactory = new CachingConnectionFactory();
    connectionFactory.setHost("localhost");
    connectionFactory.setChannelCacheSize(10);
    connectionFactory.setPort(BrokerTestUtils.getPort());
    connectionFactoryWithConfirmsEnabled = new CachingConnectionFactory();
    connectionFactoryWithConfirmsEnabled.setHost("localhost");
    // When using publisher confirms, the cache size needs to be large enough
    // otherwise channels can be closed before confirms are received.
    connectionFactoryWithConfirmsEnabled.setChannelCacheSize(100);
    connectionFactoryWithConfirmsEnabled.setPort(BrokerTestUtils.getPort());
    connectionFactoryWithConfirmsEnabled.setPublisherConfirms(true);
    templateWithConfirmsEnabled = new RabbitTemplate(connectionFactoryWithConfirmsEnabled);
    connectionFactoryWithReturnsEnabled = new CachingConnectionFactory();
    connectionFactoryWithReturnsEnabled.setHost("localhost");
    connectionFactoryWithReturnsEnabled.setChannelCacheSize(1);
    connectionFactoryWithReturnsEnabled.setPort(BrokerTestUtils.getPort());
    connectionFactoryWithReturnsEnabled.setPublisherReturns(true);
    templateWithReturnsEnabled = new RabbitTemplate(connectionFactoryWithReturnsEnabled);
}

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

@Test
public void testPublisherConfirmReceivedTwoTemplates() throws Exception {
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    templateWithConfirmsEnabled.setConfirmCallback((correlationData, ack, cause) -> latch1.countDown());
    templateWithConfirmsEnabled.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc"));
    RabbitTemplate secondTemplate = new RabbitTemplate(connectionFactoryWithConfirmsEnabled);
    secondTemplate.setConfirmCallback((correlationData, ack, cause) -> latch2.countDown());
    secondTemplate.convertAndSend(ROUTE, (Object) "message", new CorrelationData("def"));
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1));
    assertNull(secondTemplate.getUnconfirmed(-1));
}

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

@Test
public void testPublisherConfirmNotReceived() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);
    when(mockChannel.isOpen()).thenReturn(true);

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    doReturn(new PublisherCallbackChannelImpl(mockChannel)).when(mockConnection).createChannel();

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setPublisherConfirms(true);//from  w w  w.  j a v  a  2s . c  o m
    final RabbitTemplate template = new RabbitTemplate(ccf);

    final AtomicBoolean confirmed = new AtomicBoolean();
    template.setConfirmCallback((correlationData, ack, cause) -> confirmed.set(true));
    template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc"));
    Thread.sleep(5);
    assertEquals(1, template.getUnconfirmedCount());
    Collection<CorrelationData> unconfirmed = template.getUnconfirmed(-1);
    assertEquals(0, template.getUnconfirmedCount());
    assertEquals(1, unconfirmed.size());
    assertEquals("abc", unconfirmed.iterator().next().getId());
    assertFalse(confirmed.get());
}