Example usage for org.springframework.amqp.core MessageProperties setMessageId

List of usage examples for org.springframework.amqp.core MessageProperties setMessageId

Introduction

In this page you can find the example usage for org.springframework.amqp.core MessageProperties setMessageId.

Prototype

public void setMessageId(String messageId) 

Source Link

Usage

From source file:amqp.spring.camel.component.SpringAMQPMessage.java

public Message toAMQPMessage(MessageConverter msgConverter) {
    MessageProperties properties = new MessageProperties();
    properties.setMessageId(this.getMessageId());

    Message amqpMessage;//  w ww.  j a v a 2 s  . c o  m
    if (this.getBody() != null) {
        amqpMessage = msgConverter.toMessage(this.getBody(), properties);

        if (LOG.isTraceEnabled()) {
            String asText = new String(amqpMessage.getBody());
            LOG.trace("Translating To AMQP Message: " + asText);
        }
    } else {
        amqpMessage = new Message(new byte[] {}, properties);
    }

    return new HeadersPostProcessor(this).postProcessMessage(amqpMessage);
}

From source file:weChat.amqp.RpcTest.java

/**
 * Sends a message to a service that upcases the String and returns as a
 * reply using a {@link RabbitTemplate} configured with a fixed reply queue
 * and reply listener, configured with JavaConfig.
 *///from   w  ww  . ja v a 2  s .c o m
@Test
public void test() {
    AmqpReqParam param = new AmqpReqParam();
    param.setCmdid("WJ007");
    param.setCompanycode("01103");
    param.setWechatpubinfoid(1);
    BaseDto dto = new BaseDto();
    dto.put("cardnum", "5000011");
    param.setParams(dto);
    //String corrId = UUID.randomUUID().toString();
    String corrId = FixedReplyQueueConfig.responseQueue;
    Object resp = rabbitTemplate.convertSendAndReceive(FixedReplyQueueConfig.routing, param, (message) -> {
        MessageProperties properities = message.getMessageProperties();

        System.out.println("corrId:" + corrId);
        properities.setCorrelationId(corrId.getBytes());
        properities.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
        properities.setTimestamp(new Date());
        long currentTimeMillis = System.currentTimeMillis();
        properities.setMessageId(String.valueOf(currentTimeMillis));
        properities.setExpiration(String.valueOf(50000));
        properities.setContentEncoding(corrId);

        return message;
    });
    System.out.println("?" + resp);
}

From source file:weChat.amqp.JavaConfigFixedReplyQueueTests.java

/**
 * Sends a message to a service that upcases the String and returns as a
 * reply using a {@link RabbitTemplate} configured with a fixed reply queue
 * and reply listener, configured with JavaConfig.
 *//*from w  w  w. j a  va 2s  . c om*/
@Test
public void test() {
    AmqpReqParam param = new AmqpReqParam();
    param.setCmdid("WJ007");
    param.setCompanycode("00111");
    param.setWechatpubinfoid(1);
    BaseDto dto = new BaseDto();
    dto.put("cardnum", "5000028");
    param.setParams(dto);
    AmqpRespParam resp = (AmqpRespParam) rabbitTemplate.convertSendAndReceive(param, (message) -> {
        MessageProperties properities = message.getMessageProperties();
        String corrId = UUID.randomUUID().toString();
        properities.setCorrelationId(corrId.getBytes());
        properities.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
        properities.setTimestamp(new Date());
        long currentTimeMillis = System.currentTimeMillis();
        properities.setMessageId(String.valueOf(currentTimeMillis));

        return message;
    });
    System.out.println(resp);
}

From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java

@SuppressWarnings("rawtypes")
@Test//  w w  w .  ja v a  2 s  .  c  o  m
public void testWithId() throws Exception {
    // 2 messages; each retried twice by retry interceptor
    this.latch = new CountDownLatch(6);
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml",
            this.getClass());
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setMessageListener(new MessageListenerAdapter(new POJO()));
    container.setQueueNames("retry.test.queue");

    StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean();

    // use an external template so we can share his cache
    RetryTemplate retryTemplate = new RetryTemplate();
    RetryContextCache cache = spy(new MapRetryContextCache());
    retryTemplate.setRetryContextCache(cache);
    fb.setRetryOperations(retryTemplate);
    fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer());

    Advice retryInterceptor = fb.getObject();
    container.setAdviceChain(retryInterceptor);
    container.start();

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("text/plain");
    messageProperties.setMessageId("foo");
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    template.send("retry.test.exchange", "retry.test.binding", message);
    template.send("retry.test.exchange", "retry.test.binding", message);
    try {
        assertTrue(latch.await(30, TimeUnit.SECONDS));
        Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map");
        int n = 0;
        while (n++ < 100 && map.size() != 0) {
            Thread.sleep(100);
        }
        ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class);
        verify(cache, times(6)).put(putCaptor.capture(), any(RetryContext.class));
        verify(cache, times(6)).get(getCaptor.capture());
        verify(cache, atLeast(2)).remove(removeCaptor.capture());
        verify(cache, atMost(4)).remove(removeCaptor.capture());
        logger.debug("puts:" + putCaptor.getAllValues());
        logger.debug("gets:" + putCaptor.getAllValues());
        logger.debug("removes:" + removeCaptor.getAllValues());
        assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size());
    } finally {
        container.stop();
        ctx.close();
    }
}

From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java

@SuppressWarnings("rawtypes")
@Test/*from ww  w. j a va  2s.com*/
public void testWithIdAndSuccess() throws Exception {
    // 2 messages; each retried twice by retry interceptor
    this.latch = new CountDownLatch(6);
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml",
            this.getClass());
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    final Set<String> processed = new HashSet<>();
    final CountDownLatch latch = new CountDownLatch(4);
    container.setMessageListener(m -> {
        latch.countDown();
        if (!processed.contains(m.getMessageProperties().getMessageId())) {
            processed.add(m.getMessageProperties().getMessageId());
            throw new RuntimeException("fail");
        }
    });
    container.setQueueNames("retry.test.queue");

    StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean();

    // use an external template so we can share his cache
    RetryTemplate retryTemplate = new RetryTemplate();
    RetryContextCache cache = spy(new MapRetryContextCache());
    retryTemplate.setRetryContextCache(cache);
    fb.setRetryOperations(retryTemplate);
    fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer());

    Advice retryInterceptor = fb.getObject();
    container.setAdviceChain(retryInterceptor);
    container.start();

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("text/plain");
    messageProperties.setMessageId("foo");
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    template.send("retry.test.exchange", "retry.test.binding", message);
    messageProperties.setMessageId("bar");
    template.send("retry.test.exchange", "retry.test.binding", message);
    try {
        assertTrue(latch.await(30, TimeUnit.SECONDS));
        Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map");
        int n = 0;
        while (n++ < 100 && map.size() != 0) {
            Thread.sleep(100);
        }
        ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class);
        verify(cache, times(2)).put(putCaptor.capture(), any(RetryContext.class));
        verify(cache, times(2)).get(getCaptor.capture());
        verify(cache, atLeast(2)).remove(removeCaptor.capture());
        verify(cache, atMost(4)).remove(removeCaptor.capture());
        logger.debug("puts:" + putCaptor.getAllValues());
        logger.debug("gets:" + putCaptor.getAllValues());
        logger.debug("removes:" + removeCaptor.getAllValues());
        assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size());
    } finally {
        container.stop();
        ctx.close();
    }
}

From source file:org.springframework.amqp.rabbit.retry.MissingMessageIdAdvice.java

public Object invoke(MethodInvocation invocation) throws Throwable {
    String id = null;/* w ww .j av a  2 s  .  c  o m*/
    boolean redelivered = false;
    try {
        Message message = (Message) invocation.getArguments()[1];
        MessageProperties messageProperties = message.getMessageProperties();
        if (messageProperties.getMessageId() == null) {
            id = UUID.randomUUID().toString();
            messageProperties.setMessageId(id);
        }
        redelivered = messageProperties.isRedelivered();
        return invocation.proceed();
    } catch (Throwable t) {
        if (id != null && redelivered) {
            if (logger.isDebugEnabled()) {
                logger.debug("Canceling delivery of retried message that has no ID");
            }
            throw new ListenerExecutionFailedException("Cannot retry message without an ID",
                    new AmqpRejectAndDontRequeueException(t));
        } else {
            throw t;
        }
    } finally {
        if (id != null) {
            retryContextCache.remove(id);
        }
    }
}

From source file:org.springframework.amqp.rabbit.support.RabbitUtils.java

public static MessageProperties createMessageProperties(final BasicProperties source, final Envelope envelope,
        final String charset) {
    MessageProperties target = new MessageProperties();
    Map<String, Object> headers = source.getHeaders();
    if (!CollectionUtils.isEmpty(headers)) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            target.setHeader(entry.getKey(), entry.getValue());
        }// www .  j a v a2  s.  c  o m
    }
    target.setTimestamp(source.getTimestamp());
    target.setMessageId(source.getMessageId());
    target.setUserId(source.getUserId());
    target.setAppId(source.getAppId());
    target.setClusterId(source.getClusterId());
    target.setType(source.getType());
    Integer deliverMode = source.getDeliveryMode();
    if (deliverMode != null) {
        target.setDeliveryMode(MessageDeliveryMode.fromInt(deliverMode));
    }
    target.setExpiration(source.getExpiration());
    target.setPriority(source.getPriority());
    target.setContentType(source.getContentType());
    target.setContentEncoding(source.getContentEncoding());
    String correlationId = source.getCorrelationId();
    if (correlationId != null) {
        try {
            target.setCorrelationId(source.getCorrelationId().getBytes(charset));
        } catch (UnsupportedEncodingException ex) {
            throw new AmqpUnsupportedEncodingException(ex);
        }
    }
    String replyTo = source.getReplyTo();
    if (replyTo != null) {
        target.setReplyTo(new Address(replyTo));
    }
    if (envelope != null) {
        target.setReceivedExchange(envelope.getExchange());
        target.setReceivedRoutingKey(envelope.getRoutingKey());
        target.setRedelivered(envelope.isRedeliver());
        target.setDeliveryTag(envelope.getDeliveryTag());
    }
    // TODO: what about messageCount?
    return target;
}