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

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

Introduction

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

Prototype

@Override
    public void convertAndSend(Object message, MessagePostProcessor messagePostProcessor) throws AmqpException 

Source Link

Usage

From source file:com.github.liyp.rabbitmq.demo.Main.java

public static void main(String[] args) throws IOException, InterruptedException {
    // start spring context
    @SuppressWarnings({ "resource" })
    ApplicationContext context = new ClassPathXmlApplicationContext(
            "com/github/liyp/rabbitmq/demo/applicationContext.xml");

    RabbitTemplate rabbitTemplate = (RabbitTemplate) context.getBean("rabbitTemplate");
    for (int i = 0; i < 200; i++) {
        rabbitTemplate.convertAndSend("queue_one", "test queue 1 " + i);
        rabbitTemplate.convertAndSend("queue_two", new MsgBean("test queue 2 " + i));
    }//from   ww  w  .j a  va  2s. co  m
    Thread.sleep(5000);
    ThreadPoolTaskExecutor threadExe = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
    System.out.println(threadExe.getActiveCount());
    System.out.println(threadExe.getCorePoolSize());
    System.out.println(threadExe.getMaxPoolSize());
    System.out.println(threadExe.getPoolSize());
    System.out.println(threadExe.getThreadPoolExecutor().getCorePoolSize());

    // System.out.println("rsv: " +
    // rabbitTemplate.receiveAndConvert("queue_two"));
}

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  a v a 2s  .c  o m
}

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);//  www.j a  va 2 s .c om
    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 testErrorHandler() throws Exception {
    brokerRunning.deleteQueues(Q1);/*from w  ww .j av  a  2  s. c o m*/
    Queue q1 = new Queue(Q1, true, false, false, new ArgumentBuilder().put("x-dead-letter-exchange", "")
            .put("x-dead-letter-routing-key", DLQ1).get());
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    RabbitAdmin admin = new RabbitAdmin(cf);
    admin.declareQueue(q1);
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setQueueNames(Q1);
    container.setConsumersPerQueue(2);
    final AtomicReference<Channel> channel = new AtomicReference<>();
    container.setMessageListener((ChannelAwareMessageListener) (m, c) -> {
        channel.set(c);
        throw new MessageConversionException(
                "intended - should be wrapped in an AmqpRejectAndDontRequeueException");
    });
    container.setBeanName("errorHandler");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    RabbitTemplate template = new RabbitTemplate(cf);
    template.convertAndSend(Q1, "foo");
    assertNotNull(template.receive(DLQ1, 10000));
    container.stop();
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size());
    assertFalse(channel.get().isOpen());
    cf.destroy();
}

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

@Test
public void testDeferredAcks() throws Exception {
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    final CountDownLatch latch = new CountDownLatch(2);
    container.setMessageListener(m -> {
        latch.countDown();//from   w  w  w . ja va 2s .c  om
    });
    container.setQueueNames(Q1);
    container.setBeanName("deferredAcks");
    container.setMessagesPerAck(2);
    container.afterPropertiesSet();
    container.start();
    RabbitTemplate rabbitTemplate = new RabbitTemplate(cf);
    rabbitTemplate.convertAndSend(Q1, "foo");
    rabbitTemplate.convertAndSend(Q1, "bar");
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    container.stop();
    cf.stop();
    cf.destroy();
}

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

@Test
public void testErrorHandler() throws Exception {
    brokerRunning.getAdmin().deleteQueue(Q1);
    Queue q1 = new Queue(Q1, true, false, false, new ArgumentBuilder().put("x-dead-letter-exchange", "")
            .put("x-dead-letter-routing-key", DLQ1).get());
    brokerRunning.getAdmin().declareQueue(q1);
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setQueueNames(Q1);//from  w  w  w . j a  va  2 s  . co m
    container.setConsumersPerQueue(2);
    final AtomicReference<Channel> channel = new AtomicReference<>();
    container.setMessageListener((ChannelAwareMessageListener) (m, c) -> {
        channel.set(c);
        throw new MessageConversionException(
                "intended - should be wrapped in an AmqpRejectAndDontRequeueException");
    });
    container.setBeanName("errorHandler");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    RabbitTemplate template = new RabbitTemplate(cf);
    template.convertAndSend(Q1, "foo");
    assertNotNull(template.receive(DLQ1, 10000));
    container.stop();
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size());
    assertFalse(channel.get().isOpen());
    cf.destroy();
}

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

private void doTest(int concurrentConsumers, ContainerConfigurer configurer) {
    int messageCount = 10;
    RabbitTemplate template = new RabbitTemplate();
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setChannelCacheSize(concurrentConsumers);
    connectionFactory.setPort(BrokerTestUtils.getPort());
    template.setConnectionFactory(connectionFactory);
    SimpleMessageConverter messageConverter = new SimpleMessageConverter();
    messageConverter.setCreateMessageIds(true);
    template.setMessageConverter(messageConverter);
    for (int i = 0; i < messageCount; i++) {
        template.convertAndSend(queue1.getName(), new Integer(i));
        template.convertAndSend(queue2.getName(), new Integer(i));
    }/* w  w w .j  a v  a  2  s  .c  o  m*/
    final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    final CountDownLatch latch = new CountDownLatch(messageCount * 2);
    PojoListener listener = new PojoListener(latch);
    container.setMessageListener(new MessageListenerAdapter(listener));
    container.setAcknowledgeMode(AcknowledgeMode.AUTO);
    container.setChannelTransacted(true);
    container.setConcurrentConsumers(concurrentConsumers);
    configurer.configure(container);
    container.afterPropertiesSet();
    container.start();
    try {
        int timeout = Math.min(1 + messageCount / concurrentConsumers, 30);
        boolean waited = latch.await(timeout, TimeUnit.SECONDS);
        logger.info("All messages recovered: " + waited);
        assertEquals(concurrentConsumers, container.getActiveConsumerCount());
        assertTrue("Timed out waiting for messages", waited);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IllegalStateException("unexpected interruption");
    } finally {
        container.shutdown();
        assertEquals(0, container.getActiveConsumerCount());
    }
    assertNull(template.receiveAndConvert(queue1.getName()));
    assertNull(template.receiveAndConvert(queue2.getName()));
}

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

private void testChangeConsumerCountGuts(boolean transacted) throws Exception {
    final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory("localhost");
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
    try {/*w  w  w .  j a  va  2s  . com*/
        container.setMessageListener(new MessageListenerAdapter(this));
        container.setQueueNames("foo");
        container.setAutoStartup(false);
        container.setConcurrentConsumers(2);
        container.setChannelTransacted(transacted);
        container.afterPropertiesSet();
        assertEquals(2, ReflectionTestUtils.getField(container, "concurrentConsumers"));
        container.start();
        waitForNConsumers(container, 2);
        container.setConcurrentConsumers(1);
        waitForNConsumers(container, 1);
        container.setMaxConcurrentConsumers(3);
        RabbitTemplate template = new RabbitTemplate(singleConnectionFactory);
        for (int i = 0; i < 20; i++) {
            template.convertAndSend("foo", "foo");
        }
        waitForNConsumers(container, 2); // increased consumers due to work
        waitForNConsumers(container, 1, 20000); // should stop the extra consumer after 10 seconds idle
        container.setConcurrentConsumers(3);
        waitForNConsumers(container, 3);
        container.stop();
        waitForNConsumers(container, 0);
        singleConnectionFactory.destroy();
    } finally {
        container.stop();
    }
}