Example usage for org.springframework.amqp.support.converter SimpleMessageConverter SimpleMessageConverter

List of usage examples for org.springframework.amqp.support.converter SimpleMessageConverter SimpleMessageConverter

Introduction

In this page you can find the example usage for org.springframework.amqp.support.converter SimpleMessageConverter SimpleMessageConverter.

Prototype

SimpleMessageConverter

Source Link

Usage

From source file:org.kurento.rabbitmq.RabbitTemplate.java

/**
 * Set up the default strategies. Subclasses can override if necessary.
 *///w w w. j a v a  2s  .  c o m
protected void initDefaultStrategies() {
    setMessageConverter(new SimpleMessageConverter());
}

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

@Test
public void testSendAndReceiveInCallback() throws Exception {
    template.convertAndSend(ROUTE, "message");
    final MessagePropertiesConverter messagePropertiesConverter = new DefaultMessagePropertiesConverter();
    String result = template.execute(new ChannelCallback<String>() {
        public String doInRabbit(Channel channel) throws Exception {
            // We need noAck=false here for the message to be expicitly
            // acked
            GetResponse response = channel.basicGet(ROUTE, false);
            MessageProperties messageProps = messagePropertiesConverter.toMessageProperties(response.getProps(),
                    response.getEnvelope(), "UTF-8");
            // Explicit ack
            channel.basicAck(response.getEnvelope().getDeliveryTag(), false);
            return (String) new SimpleMessageConverter()
                    .fromMessage(new Message(response.getBody(), messageProps));
        }//from   ww w . ja  va 2  s  .  c  o  m
    });
    assertEquals("message", result);
    result = (String) template.receiveAndConvert(ROUTE);
    assertEquals(null, result);
}

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

@Test
public void testPublisherConfirmReceivedConcurrentThreads() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    templateWithConfirmsEnabled.setConfirmCallback((correlationData, ack, cause) -> latch.countDown());

    // Hold up the first thread so we get two channels
    final CountDownLatch threadLatch = new CountDownLatch(1);
    //Thread 1//w  w  w .  j a v a 2  s.c o  m
    Executors.newSingleThreadExecutor().execute(() -> templateWithConfirmsEnabled.execute(channel -> {
        try {
            threadLatch.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        templateWithConfirmsEnabled.doSend(channel, "", ROUTE,
                new SimpleMessageConverter().toMessage("message", new MessageProperties()), false,
                new CorrelationData("def"));
        return null;
    }));

    // Thread 2
    templateWithConfirmsEnabled.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc"));
    threadLatch.countDown();
    assertTrue(latch.await(5000, TimeUnit.MILLISECONDS));
    assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1));
}

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

@Test
public void testPublisherConfirmNotReceivedMultiThreads() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);
    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);
    when(mockChannel1.getNextPublishSeqNo()).thenReturn(1L, 2L, 3L, 4L);
    when(mockChannel2.getNextPublishSeqNo()).thenReturn(1L, 2L, 3L, 4L);

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    PublisherCallbackChannelImpl channel1 = new PublisherCallbackChannelImpl(mockChannel1);
    PublisherCallbackChannelImpl channel2 = new PublisherCallbackChannelImpl(mockChannel2);
    when(mockConnection.createChannel()).thenReturn(channel1).thenReturn(channel2);

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

    final AtomicBoolean confirmed = new AtomicBoolean();
    template.setConfirmCallback((correlationData, ack, cause) -> confirmed.set(true));

    // Hold up the first thread so we get two channels
    final CountDownLatch threadLatch = new CountDownLatch(1);
    final CountDownLatch threadSentLatch = new CountDownLatch(1);
    //Thread 1
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(() -> template.execute(channel -> {
        try {
            threadLatch.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        template.doSend(channel, "", ROUTE,
                new SimpleMessageConverter().toMessage("message", new MessageProperties()), false,
                new CorrelationData("def"));
        threadSentLatch.countDown();
        return null;
    }));

    // Thread 2
    template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); // channel y
    threadLatch.countDown();
    assertTrue(threadSentLatch.await(5, TimeUnit.SECONDS));
    assertEquals(2, template.getUnconfirmedCount());
    Collection<CorrelationData> unconfirmed = template.getUnconfirmed(-1);
    assertEquals(2, unconfirmed.size());
    assertEquals(0, template.getUnconfirmedCount());
    Set<String> ids = new HashSet<String>();
    Iterator<CorrelationData> iterator = unconfirmed.iterator();
    ids.add(iterator.next().getId());
    ids.add(iterator.next().getId());
    assertTrue(ids.remove("abc"));
    assertTrue(ids.remove("def"));
    assertFalse(confirmed.get());
    DirectFieldAccessor dfa = new DirectFieldAccessor(template);
    Map<?, ?> pendingConfirms = (Map<?, ?>) dfa.getPropertyValue("publisherConfirmChannels");
    assertThat(pendingConfirms.size(), greaterThan(0)); // might use 2 or only 1 channel
    exec.shutdown();
    assertTrue(exec.awaitTermination(10, TimeUnit.SECONDS));
    ccf.destroy();
    assertEquals(0, pendingConfirms.size());
}

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 ww.  ja v a 2s  .  c om*/
    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.SimpleMessageListenerWithRabbitMQ.java

public static void main(String[] args) throws InterruptedException {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
    connectionFactory.setHost("localhost");
    connectionFactory.setUsername("guest");
    connectionFactory.setPassword("guest");
    assertNotNull(connectionFactory);/* w  w  w.j a  v  a 2s  .  c  o m*/

    MessageConverter messageConverter = new SimpleMessageConverter();
    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames("foo");
    container.setPrefetchCount(1000);
    container.setTxSize(500);
    container.setAcknowledgeMode(AcknowledgeMode.AUTO);
    container.setConcurrentConsumers(20);
    container.setMessageListener(new MessageListenerAdapter(new SimpleAdapter(), messageConverter));
    container.start();

    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.setMessageConverter(messageConverter);
    List<BlockingQueue<?>> queues = getQueues(container);

    Thread.sleep(10000);
    int n = 0;
    while (true) {
        for (int i = 1; i <= 200; i++) {

            template.send("foo", "",
                    new Message(
                            "foo # ID: id".replace("#", String.valueOf(i))
                                    .replace("id", java.util.UUID.randomUUID().toString()).getBytes(),
                            messageProperties));

        }
        Thread.sleep(1000);
        if (++n % 10 == 0) {
            logger.warn(count(queues));
        }
    }
}

From source file:org.springframework.integration.amqp.channel.AbstractSubscribableAmqpChannel.java

@Override
public void onInit() throws Exception {
    super.onInit();
    this.dispatcher = this.createDispatcher();
    if (this.dispatcher instanceof AbstractDispatcher) {
        ((AbstractDispatcher) this.dispatcher).setMaxSubscribers(this.maxSubscribers);
    }//from ww w. j a v  a2  s.co m
    AmqpAdmin admin = new RabbitAdmin(this.container.getConnectionFactory());
    Queue queue = this.initializeQueue(admin, this.channelName);
    this.container.setQueues(queue);
    MessageConverter converter = (this.getAmqpTemplate() instanceof RabbitTemplate)
            ? ((RabbitTemplate) this.getAmqpTemplate()).getMessageConverter()
            : new SimpleMessageConverter();
    MessageListener listener = new DispatchingMessageListener(converter, this.dispatcher, this, this.isPubSub);
    this.container.setMessageListener(listener);
    if (!this.container.isActive()) {
        this.container.afterPropertiesSet();
    }
}