org.springframework.amqp.rabbit.connection.CorrelationData Java Examples

The following examples show how to use org.springframework.amqp.rabbit.connection.CorrelationData. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TracingRabbitTemplate.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
@Override
public void send(String exchange, String routingKey, Message message, CorrelationData correlationData) throws AmqpException {
  // used when sending reply to AMQP requests that expected response message
  // or when not waiting for reply (for example sending out events).
  if (routingKey.startsWith(Address.AMQ_RABBITMQ_REPLY_TO + ".")) {
    super.send(exchange, routingKey, message, correlationData);
    spanDecorator.onSendReply(message.getMessageProperties(), exchange, routingKey, tracer.activeSpan());
    return; // don't create new span for response messages
  }
  try {
    createTracingHelper()
        .doWithTracingHeadersMessage(exchange, routingKey, message, (messageWithTracingHeaders) -> {
          super.send(exchange, routingKey, messageWithTracingHeaders, correlationData);
          return null;
        });
  } catch (Throwable throwable) {
    Throwables.propagateIfPossible(throwable, AmqpException.class);
  }
}
 
Example #2
Source File: DefaultAmqpMessageSenderService.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void sendMessage(final Message message, final URI sendTo) {
    if (!IpUtil.isAmqpUri(sendTo)) {
        return;
    }

    final String exchange = sendTo.getPath().substring(1);
    final String correlationId = UUID.randomUUID().toString();

    if (isCorrelationIdEmpty(message)) {
        message.getMessageProperties().setCorrelationId(correlationId);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Sending message {} to exchange {} with correlationId {}", message, exchange, correlationId);
    } else {
        LOGGER.debug("Sending message to exchange {} with correlationId {}", exchange, correlationId);
    }

    getRabbitTemplate().send(exchange, null, message, new CorrelationData(correlationId));
}
 
Example #3
Source File: DmfSenderService.java    From hawkbit-examples with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Send a message if the message is not null.
 *
 * @param address
 *            the exchange name
 * @param message
 *            the amqp message which will be send if its not null
 */
public void sendMessage(final String address, final Message message) {
    if (message == null) {
        return;
    }
    message.getMessageProperties().getHeaders().remove(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME);

    final String correlationId = UUID.randomUUID().toString();

    if (isCorrelationIdEmpty(message)) {
        message.getMessageProperties().setCorrelationId(correlationId);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Sending message {} to exchange {} with correlationId {}", message, address, correlationId);
    } else {
        LOGGER.debug("Sending message to exchange {} with correlationId {}", address, correlationId);
    }

    rabbitTemplate.send(address, null, message, new CorrelationData(correlationId));
}
 
Example #4
Source File: RabbitMqSendTracingAspect.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
/**
 * @see RabbitTemplate#sendAndReceive(String, String, Message, CorrelationData)
 */
@Around(value = "execution(* org.springframework.amqp.rabbit.core.RabbitTemplate.sendAndReceive(..)) && args(exchange,"
    + "routingKey, message, correlationData)", argNames = "pjp,exchange,routingKey,message,correlationData")
public Object traceRabbitSendAndReceive(
    ProceedingJoinPoint pjp, String exchange, String routingKey, Message message, CorrelationData correlationData)
    throws Throwable {
  return createTracingHelper()
      .nullResponseMeansTimeout((RabbitTemplate) pjp.getTarget())
      .doWithTracingHeadersMessage(exchange, routingKey, message, (convertedMessage) ->
          proceedReplacingMessage(pjp, convertedMessage, 2));
}
 
Example #5
Source File: RabbitMQConfig.java    From micro-service with MIT License 5 votes vote down vote up
@Bean()
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public RabbitTemplate rabbitTemplate() {
	
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setInitialInterval(500);
	backOffPolicy.setMultiplier(10.0);
	backOffPolicy.setMaxInterval(10000);
	
	RetryTemplate retryTemplate = new RetryTemplate();
	retryTemplate.setBackOffPolicy(backOffPolicy);
	
	RabbitTemplate template = new RabbitTemplate(connectionFactory());
	template.setRetryTemplate(retryTemplate);
	template.setChannelTransacted(false);
	
	template.setConfirmCallback(new ConfirmCallback() {
		@Override
		public void confirm(CorrelationData correlationData, boolean ack, String cause) {
			if(ack) {
				logger.info("发送消息成功, correlationId={}", correlationData.getId());
			} else {
				logger.info("发送消息失败, correlationId={}, cause={}", correlationData.getId(), cause);
			}
		}
	});
	
	return template;
}
 
Example #6
Source File: Sender.java    From micro-service with MIT License 5 votes vote down vote up
@Scheduled(cron = "0/5 * *  * * ? ")
//	@Scheduled(fixedDelay = 1000 * 60 * 60)
	public void send() {
		
		Classes classes = new Classes();
		classes.setId(1);
		classes.setGrade("一年级");
		
		CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
		logger.info("发送消息, correlationId={}, message={}", correlationData.getId(), JSON.toJSONString(classes));
		
		rabbitTemplate.convertAndSend(exchangeName, null, JSON.toJSONString(classes), correlationData);
	}
 
Example #7
Source File: OrderMessageSenderTest.java    From POC with Apache License 2.0 5 votes vote down vote up
@Test
void testSendOrder() throws JsonProcessingException {
	String convertedString = "{\"orderNumber\":\"1\",\"productId\":\"P1\"," + "\"amount\":10.0}";
	// given
	given(this.objectMapper.writeValueAsString(MockObjectCreator.getOrder())).willReturn(convertedString);
	willDoNothing().given(this.rabbitTemplate).convertAndSend(eq(RabbitConfig.QUEUE_ORDERS),
			eq(this.orderMessageSender.getRabbitMQMessage(convertedString)), any(CorrelationData.class));
	// when
	this.orderMessageSender.sendOrder(MockObjectCreator.getOrder());
	verify(this.rabbitTemplate, times(1)).convertAndSend(eq(RabbitConfig.QUEUE_ORDERS),
			eq(this.orderMessageSender.getRabbitMQMessage(convertedString)), any(CorrelationData.class));
	verify(this.objectMapper, times(1)).writeValueAsString(MockObjectCreator.getOrder());
}
 
Example #8
Source File: OrderMessageSenderImpl.java    From POC with Apache License 2.0 5 votes vote down vote up
@Override
public void sendOrder(Order order) throws JsonProcessingException {
	// this.rabbitTemplate.convertAndSend(RabbitConfig.QUEUE_ORDERS, order);

	String orderJson = this.objectMapper.writeValueAsString(order);
	String correlationId = UUID.randomUUID().toString();
	this.rabbitTemplate.convertAndSend(RabbitConfig.QUEUE_ORDERS, getRabbitMQMessage(orderJson),
			new CorrelationData(correlationId));

}
 
Example #9
Source File: RabbitRegister.java    From bird-java with MIT License 5 votes vote down vote up
@Override
public void regist(IEventArg eventArg) {
    CorrelationData data = new CorrelationData();
    data.setId(eventArg.getEventId());

    rabbitTemplate.setConfirmCallback(this);
    rabbitTemplate.convertAndSend(eventArg.getClass().getName(), "", eventArg, data);
}
 
Example #10
Source File: SendController.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 发送一个消息到RabbitMQ
 * Comment by 玄玉<https://jadyer.cn/> on 2018/3/23 14:53.
 */
@ResponseBody
@GetMapping("")
public CommResult send(){
    int id = 2;
    UserMsg userMsg = new UserMsg(id, "玄玉", "https://jadyer.cn/");
    this.rabbitTemplate.convertAndSend("apply.status", "apply.status.1101.123", userMsg, new CorrelationData(id+""));
    return CommResult.success();
}
 
Example #11
Source File: RabbitMqSendTracingAspect.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
/**
 * @see RabbitTemplate#convertSendAndReceive(String, String, Object, MessagePostProcessor, CorrelationData)
 */
@Around(value = "execution(* org.springframework.amqp.rabbit.core.RabbitTemplate.convertSendAndReceive(..)) " +
                "&& args(exchange, routingKey, message, messagePostProcessor, correlationData)",
    argNames = "pjp,exchange,routingKey,message,messagePostProcessor,correlationData")
public Object traceRabbitConvertSendAndReceive(
    ProceedingJoinPoint pjp, String exchange, String routingKey, Object message,
    MessagePostProcessor messagePostProcessor, CorrelationData correlationData)
    throws Throwable {
  return createTracingHelper()
      .nullResponseMeansTimeout((RabbitTemplate) pjp.getTarget())
      .doWithTracingHeadersMessage(exchange, routingKey, message, (convertedMessage) ->
          proceedReplacingMessage(pjp, convertedMessage, 2));
}
 
Example #12
Source File: RabbitMqSendTracingAspect.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
/**
 * @see RabbitTemplate#convertAndSend(String, String, Object, CorrelationData)
 */
@Around(value = "execution(* org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(..)) " +
        "&& args(exchange, routingKey, message, correlationData)",
        argNames = "pjp,exchange,routingKey,message,correlationData")
public Object traceRabbitConvertAndSend(ProceedingJoinPoint pjp, String exchange, String routingKey, Object message,
                                        CorrelationData correlationData)
        throws Throwable {
  return createTracingHelper()
          .doWithTracingHeadersMessage(exchange, routingKey, message, (convertedMessage) ->
                  proceedReplacingMessage(pjp, convertedMessage, 2));
}
 
Example #13
Source File: RabbitMqSendTracingAspect.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
/**
 * @see RabbitTemplate#convertAndSend(String, Object, MessagePostProcessor, CorrelationData)
 */
@Around(value = "execution(* org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(..)) " +
                "&& args(routingKey, message, messagePostProcessor, correlationData)",
    argNames = "pjp,routingKey,message,messagePostProcessor,correlationData")
public Object traceRabbitConvertAndSend(ProceedingJoinPoint pjp, String routingKey, Object message,
                                        MessagePostProcessor messagePostProcessor, CorrelationData correlationData)
    throws Throwable {
  return createTracingHelper()
      .doWithTracingHeadersMessage(this.exchange, routingKey, message, (convertedMessage) ->
          proceedReplacingMessage(pjp, convertedMessage, 1));
}
 
Example #14
Source File: RabbitMqTracingAutoConfigurationDisabledItTest.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Test
public void convertAndSend_withExchangeRoutingKeyAndCorrelationData_shouldNotBeTraced() {
  // when
  rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, MESSAGE, (CorrelationData) null);

  // then
  checkNoSpans();
}
 
Example #15
Source File: RabbitMqTracingAutoConfigurationItTest.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Test
public void convertAndSend_withExchangeRoutingKeyAndCorrelationData_shouldBeTraced() {
  // given
  CorrelationData correlationData = null;
  // when
  rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, MESSAGE, correlationData);

  // then
  assertConsumerAndProducerSpans(0, ROUTING_KEY);
}
 
Example #16
Source File: RabbitMqTracingAutoConfigurationWithoutRabbitTemplateItTest.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Test
public void convertAndSend_withExchangeAndRoutingKey_shouldBeTraced() {
  // given
  RabbitTemplate rabbitTemplate = getRabbitTemplate();

  // when
  rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, MESSAGE, (CorrelationData) null);

  // then
  assertConsumerAndProducerSpans(0, ROUTING_KEY);
}
 
Example #17
Source File: TracingRabbitTemplate.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Override
protected Message doSendAndReceiveWithFixed(String exchange, String routingKey, Message message, CorrelationData correlationData) {
  try {
    return createTracingHelper()
        .doWithTracingHeadersMessage(exchange, routingKey, message, (messageWithTracingHeaders) -> {
          // returns null in case of timeout
          return super.doSendAndReceiveWithFixed(exchange, routingKey, messageWithTracingHeaders, correlationData);
        });
  } catch (Throwable throwable) {
    throw Throwables.propagate(throwable);
  }
}
 
Example #18
Source File: TracingRabbitTemplate.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Override
protected Message doSendAndReceiveWithTemporary(String exchange, String routingKey, Message message, CorrelationData correlationData) {
  try {
    return createTracingHelper()
        .nullResponseMeansTimeout(this)
        .doWithTracingHeadersMessage(exchange, routingKey, message,
            (messageWithTracingHeaders) -> super.doSendAndReceiveWithTemporary(exchange, routingKey, messageWithTracingHeaders, correlationData));
  } catch (Throwable throwable) {
    throw Throwables.propagate(throwable);
  }
}
 
Example #19
Source File: RabbitMqTracingAutoConfigurationCustomizationItTest.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Test
public void convertAndSend_withExchangeRoutingKeyAndCorrelationData_shouldBeTraced() {
  // when
  rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, MESSAGE, (CorrelationData) null);

  // then
  FinishedSpansHelper spans = awaitFinishedSpans();
  MockSpan sentSpan = spans.getSendSpan();
  MockSpan receiveSpan = spans.getReceiveSpan();

  assertOnSpans(sentSpan, receiveSpan, ROUTING_KEY);
}
 
Example #20
Source File: RabbitMqTracingManualConfigurationItTest.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Test
public void convertAndSend_withExchangeRoutingKeyAndCorrelationData_shouldBeTraced() {
  // when
  rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, MESSAGE, (CorrelationData) null);

  // then
  assertConsumerAndProducerSpans(0, ROUTING_KEY);
}
 
Example #21
Source File: RabbitMqTracingNoConfigurationItTest.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Test
public void convertAndSend_withExchangeRoutingKeyAndCorrelationData_shouldNotBeTraced() {
  // given
  CorrelationData correlationData = null;
  // when
  rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, MESSAGE, correlationData);

  // then
  checkNoSpans();
}
 
Example #22
Source File: OrderProducer.java    From SpringBoot-Course with MIT License 4 votes vote down vote up
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
    System.err.println("correlationData: " + correlationData);
    System.err.println("ack: " + ack);
    System.err.println("cause: " + cause);
}
 
Example #23
Source File: RabbitRegister.java    From bird-java with MIT License 3 votes vote down vote up
@Override
public void confirm(CorrelationData data, boolean success, String s) {

    if (success) {

    } else {

    }
}
 
Example #24
Source File: RabbitMessageSender.java    From common-project with Apache License 2.0 2 votes vote down vote up
/**
 * 发送RPC请求
 *
 * @param rpcProto RPC信息
 * @return RPC结果
 * @throws Exception 异常
 */
public RpcProto sendAndReceive(RpcProto rpcProto) throws Exception {
    CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
    Object response = rabbitTemplate.convertSendAndReceive(MqConstants.RPC_EXCHANGE, MqConstants.RPC_ROUTING_KEY, rpcProto, correlationId);
    return (RpcProto) response;
}