Java Code Examples for org.springframework.amqp.core.MessageProperties

The following examples show how to use org.springframework.amqp.core.MessageProperties. These examples are extracted from open source projects. 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 Project: common-project   Source File: ProtobufMessageConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Message toMessage(Object obj, MessageProperties messageProperties) throws MessageConversionException {
    String messageType = obj.getClass().getSimpleName();
    Codec<Object> codec = codecMap.get(messageType);
    if (codec == null) {
        throw new MessageConversionException("不支持转换的消息类型:" + messageType);
    }
    messageProperties.setHeader("messageType", messageType);
    byte[] body;
    try {
        body = codec.encode(obj);
    } catch (Exception e) {
        throw new MessageConversionException("编码失败:" + messageType, e);
    }
    return new Message(body, messageProperties);
}
 
Example 2
Source Project: elasticactors   Source File: RabbitTemplateMessageQueue.java    License: Apache License 2.0 6 votes vote down vote up
private MessageProperties createProps(InternalMessage message) {
    MessageBuilderSupport<MessageProperties> messageBuilderSupport =
            MessagePropertiesBuilder.newInstance()
                    .setContentType(MessageProperties.CONTENT_TYPE_BYTES)
                    .setDeliveryMode(message.isDurable()
                            ? MessageDeliveryMode.PERSISTENT
                            : MessageDeliveryMode.NON_PERSISTENT);
    if (message.getTimeout() < 0) {
        return messageBuilderSupport.build();
    } else {
        return messageBuilderSupport
                .setPriority(MessageProperties.DEFAULT_PRIORITY)
                .setExpiration(String.valueOf(message.getTimeout()))
                .build();
    }
}
 
Example 3
private void sendReplyIfRequested(Message message) {
  MessageProperties messageProperties = message.getMessageProperties();
  String replyToProperty = messageProperties.getReplyTo();

  if (replyToProperty != null) {
    RabbitTemplate rabbitTemplate = rabbitTemplateProvider.getRabbitTemplate();
    Address replyTo = new Address(replyToProperty);
    String replyMsg = REPLY_MSG_PREFIX + new String(message.getBody(), UTF_8);
    Message replyMessage = rabbitTemplate.getMessageConverter().toMessage(replyMsg, null);

    Object addCustomResponseErrorMarkerHeader = messageProperties.getHeaders()
        .get(HEADER_ADD_CUSTOM_ERROR_HEADER_TO_RESPONSE);

    if (addCustomResponseErrorMarkerHeader != null) {
      replyMessage.getMessageProperties().setHeader(HEADER_CUSTOM_RESPONSE_ERROR_MARKER_HEADER, "dummy error message");
    }
    replyMessage.getMessageProperties().setCorrelationId(messageProperties.getCorrelationId());

    rabbitTemplate.convertAndSend(replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage);
  }
}
 
Example 4
@Test
@Description("Tests the creation of a target/thing by calling the same method that incoming RabbitMQ messages would access.")
public void createThing() {
    final String knownThingId = "1";
    final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED);
    messageProperties.setHeader(MessageHeaderKey.THING_ID, "1");
    final Message message = messageConverter.toMessage(new byte[0], messageProperties);

    final Target targetMock = mock(Target.class);

    final ArgumentCaptor<String> targetIdCaptor = ArgumentCaptor.forClass(String.class);
    final ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class);
    when(controllerManagementMock.findOrRegisterTargetIfItDoesNotExist(targetIdCaptor.capture(),
            uriCaptor.capture())).thenReturn(targetMock);
    when(controllerManagementMock.findActiveActionWithHighestWeight(any())).thenReturn(Optional.empty());

    amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, VIRTUAL_HOST);

    // verify
    assertThat(targetIdCaptor.getValue()).as("Thing id is wrong").isEqualTo(knownThingId);
    assertThat(uriCaptor.getValue().toString()).as("Uri is not right")
            .isEqualTo("amqp://" + VIRTUAL_HOST + "/MyTest");
}
 
Example 5
private Message doBefore(String exchange, String routingKey, Object message) {

    Message convertedMessage = convertMessageIfNecessary(message);

    final MessageProperties messageProperties = convertedMessage.getMessageProperties();

    // Add tracing header to outgoing AMQP message
    // so that new spans created on the AMQP message consumer side could be associated with span of current trace
    scope = RabbitMqTracingUtils.buildSendSpan(tracer, messageProperties);
    tracer.inject(
        tracer.scopeManager().activeSpan().context(),
        Format.Builtin.TEXT_MAP,
        new RabbitMqInjectAdapter(messageProperties));

    // Add AMQP related tags to tracing span
    spanDecorator.onSend(messageProperties, exchange, routingKey, tracer.scopeManager().activeSpan());

    return convertedMessage;
  }
 
Example 6
Source Project: java-spring-rabbitmq   Source File: RabbitMqTracingUtils.java    License: Apache License 2.0 6 votes vote down vote up
static Scope buildSendSpan(Tracer tracer, MessageProperties messageProperties) {
  Tracer.SpanBuilder spanBuilder =
      tracer
          .buildSpan(RabbitMqTracingTags.SPAN_KIND_PRODUCER)
          .ignoreActiveSpan()
          .withTag(Tags.SPAN_KIND.getKey(), RabbitMqTracingTags.SPAN_KIND_PRODUCER);

  ScopeManager scopeManager = tracer.scopeManager();
  Optional<SpanContext> existingSpanContext = Optional.ofNullable(scopeManager)
      .map(ScopeManager::activeSpan)
      .map(Span::context);

  existingSpanContext.ifPresent(spanBuilder::asChildOf);

  if (messageProperties.getHeaders() != null) {
    Optional<SpanContext> messageParentContext = findParent(messageProperties, tracer);
    messageParentContext.ifPresent(spanBuilder::asChildOf);
  }
  Span span = spanBuilder.start();
  return scopeManager.activate(span);
}
 
Example 7
@Test(expected = RuntimeException.class)
public void testTraceRabbitSend_whenException() throws Throwable {
  // given
  String exchange = "opentracing.event.exchange";

  MessageProperties properties = new MessageProperties();
  Message message = new Message("".getBytes(), properties);
  Object[] args = new Object[] {exchange, ROUTING_KEY, message};
  given(proceedingJoinPoint.getArgs()).willReturn(args);

  given(messageConverter.toMessage(any(Object.class), any(MessageProperties.class)))
      .willReturn(message);

  given(proceedingJoinPoint.proceed(args)).willThrow(new RuntimeException());

  try {
    // when
    aspect.traceRabbitSend(proceedingJoinPoint, exchange, ROUTING_KEY, message);
  } catch (RuntimeException e) {
    // then
    verify(proceedingJoinPoint).getArgs();
    verify(proceedingJoinPoint).proceed(args);

    throw e;
  }
}
 
Example 8
Source Project: zxl   Source File: MQServer.java    License: Apache License 2.0 6 votes vote down vote up
private void replyIfNecessary(Message message, Object result, RabbitTemplate mqTemplate) {
	MessageProperties messageProperties = message.getMessageProperties();
	String correlationId = null;
	try {
		correlationId = new String(messageProperties.getCorrelationId(), DEFAULT_CHARSET);
	} catch (Exception ignored) {
		try {
			correlationId = (String) SerializationUtils.deserialize(messageProperties.getCorrelationId());
		} catch (Exception warnException) {
			LogUtil.warn(logger, "#####获取correlationId失败,可能导致客户端挂起", warnException);
		}
	}
	boolean isNecessary = result != null && messageProperties.getReplyTo() != null;
	if (isNecessary) {
		mqTemplate.send(messageProperties.getReplyTo(), correlationId == null ? mqMessageConverter.toSendMessage(result) : mqMessageConverter.toReplyMessage(result, correlationId));
	}
}
 
Example 9
@Test
@Description("Tests the target attribute update by calling the same method that incoming RabbitMQ messages would access.")
public void updateAttributes() {
    final String knownThingId = "1";
    final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
    messageProperties.setHeader(MessageHeaderKey.THING_ID, knownThingId);
    messageProperties.setHeader(MessageHeaderKey.TOPIC, "UPDATE_ATTRIBUTES");
    final DmfAttributeUpdate attributeUpdate = new DmfAttributeUpdate();
    attributeUpdate.getAttributes().put("testKey1", "testValue1");
    attributeUpdate.getAttributes().put("testKey2", "testValue2");

    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(attributeUpdate,
            messageProperties);

    when(controllerManagementMock.updateControllerAttributes(targetIdCaptor.capture(), attributesCaptor.capture(),
            modeCaptor.capture())).thenReturn(null);

    amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, VIRTUAL_HOST);

    // verify
    assertThat(targetIdCaptor.getValue()).as("Thing id is wrong").isEqualTo(knownThingId);
    assertThat(attributesCaptor.getValue()).as("Attributes is not right")
            .isEqualTo(attributeUpdate.getAttributes());
}
 
Example 10
/**
 * Incoming messages
 */
@Override
public MessageProperties toMessageProperties(AMQP.BasicProperties source, Envelope envelope, String charset) {
	final MessageProperties messageProperties = super.toMessageProperties(source, envelope, charset);

	final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);
	if (filterConfiguration.shouldProcessContext(AsyncProcess)) {
		// Values are stored as type of LongStringHelper.ByteArrayLongString - but it's private
		final Map<String, String> traceeContextMap = transformToTraceeContextMap(
			(Map<String, ?>) messageProperties.getHeaders().get(TPIC_HEADER));
		if (traceeContextMap != null && !traceeContextMap.isEmpty()) {
			backend.putAll(filterConfiguration.filterDeniedParams(traceeContextMap, AsyncProcess));
		}
	}

	Utilities.generateInvocationIdIfNecessary(backend);
	return messageProperties;
}
 
Example 11
Source Project: sinavi-jfw   Source File: ExceptionMessageExchangerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void AbstractAmqpExceptionを継承した例外の場合は例外IDがヘッダに設定される() {
    class AmqpException extends AmqpApplicationRecoverableException {
        private static final long serialVersionUID = 1L;
        public AmqpException(String code, String routingKey) {
            super(code, routingKey);
        }
    }
    AmqpException e = new AmqpException("code", "dummy");
    exchanger.recover(message, e);
    ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    ArgumentCaptor<String> routingKeyCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> exchangeCaptor = ArgumentCaptor.forClass(String.class);
    verify(mock).send(exchangeCaptor.capture(), routingKeyCaptor.capture(), messageCaptor.capture());
    MessageProperties prop = messageCaptor.getValue().getMessageProperties();
    assertThat(prop.getHeaders().get("x-exception-stacktrace").toString(), is(ExceptionUtils.getStackTrace(e)));
    assertThat(prop.getHeaders().get("x-exception-message").toString(), is(e.getMessage()));
    assertThat(prop.getHeaders().get("x-original-exchange").toString(), is("the.original.exchange"));
    assertThat(prop.getHeaders().get("x-original-routing-key").toString(), is("the.original.routing-key"));
    assertThat(prop.getHeaders().get("x-exception-id").toString(), is(e.getId()));
    assertThat(exchangeCaptor.getValue(), is("error.exchange"));
    assertThat(routingKeyCaptor.getValue(), is(e.getRoutingKey()));
}
 
Example 12
Source Project: konker-platform   Source File: RabbitGateway.java    License: Apache License 2.0 6 votes vote down vote up
public void queueEvent(Device device, EventRoute eventRoute, Event event) {
    try {
        MessageProperties properties = new MessageProperties();
        properties.setHeader(RabbitMQDataConfig.MSG_HEADER_APIKEY, device.getApiKey());
        properties.setHeader(RabbitMQDataConfig.MSG_HEADER_EVENT_ROUTE_GUID, eventRoute.getGuid());

        Message message = new Message(toByteArray(event), properties);
        rabbitTemplate.convertAndSend("routed.events", message);

        if (!event.getIncoming().getChannel().equals("_echo")) {
            LOGGER.info(MessageFormat.format("Output tenant: {0} app: {1} channel: {2} device: {3} ts: {4} size: {5}",
                    device.getTenant().getDomainName(),
                    device.getApplication().getName(),
                    eventRoute.getOutgoing().getData().get("channel"),
                    eventRoute.getOutgoing().getDisplayName(),
                    event.getCreationTimestamp(),
                    event.getPayload().getBytes().length));

        }

    } catch (AmqpException ex) {
        LOGGER.error("AmqpException while sending message to RabbitMQ...", ex);
    }
}
 
Example 13
Source Project: konker-platform   Source File: EventPublisherDeviceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotSendAnyEventThroughGatewayIfDeviceIsDisabled() throws Exception {
    Tenant tenant = tenantRepository.findByDomainName("konker");
    Application application = applicationRepository.findByTenantAndName(tenant.getId(), "smartffkonker");

    Optional.of(deviceRegisterService.findByTenantDomainNameAndDeviceGuid(REGISTERED_TENANT_DOMAIN,REGISTERED_DEVICE_GUID))
        .filter(device -> !device.isActive())
        .orElseGet(() -> deviceRegisterService.switchEnabledDisabled(tenant, application, THE_DEVICE_GUID).getResult());

    subject.send(event,destinationUri,data,device.getTenant(),device.getApplication());

    MessageProperties properties = new MessageProperties();
    properties.setHeader(RabbitMQDataConfig.MSG_HEADER_APIKEY, device.getApiKey());
    properties.setHeader(RabbitMQDataConfig.MSG_HEADER_CHANNEL, data.get(DEVICE_MQTT_CHANNEL));

    Message message = new Message(event.getPayload().getBytes("UTF-8"), properties);

    verify(rabbitTemplate,never()).convertAndSend("data.sub", message);
    verify(deviceLogEventService,never()).logIncomingEvent(Mockito.any() , Mockito.any());
    verify(deviceLogEventService,never()).logOutgoingEvent(Mockito.any() , Mockito.any());
}
 
Example 14
@Test
public void testBadRepublishSetting() throws IOException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection conn = mock(Connection.class);
	given(cf.createConnection()).willReturn(conn);
	Channel channel = mock(Channel.class);
	given(channel.isOpen()).willReturn(true);
	given(channel.exchangeDeclarePassive("DLX")).willThrow(new IOException());
	given(conn.createChannel(false)).willReturn(channel);
	RabbitProperties props = new RabbitProperties();
	RabbitMessageChannelBinder binder = new RabbitMessageChannelBinder(cf, props, null);
	RabbitConsumerProperties extension = new RabbitConsumerProperties();
	ExtendedConsumerProperties<RabbitConsumerProperties> bindingProps =
			new ExtendedConsumerProperties<RabbitConsumerProperties>(extension);
	MessageHandler handler = binder.getErrorMessageHandler(mock(ConsumerDestination.class), "foo", bindingProps);
	ErrorMessage message = new ErrorMessage(new RuntimeException("test"),
			Collections.singletonMap(IntegrationMessageHeaderAccessor.SOURCE_DATA,
					new Message("foo".getBytes(), new MessageProperties())));
	handler.handleMessage(message);
	handler.handleMessage(message);
	verify(channel, times(1)).exchangeDeclarePassive("DLX");
	verify(channel, never()).basicPublish(any(), any(), eq(false), any(), any());
}
 
Example 15
Source Project: brave   Source File: TracingRabbitListenerAdviceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void continues_parent_trace() throws Throwable {
  MessageProperties props = new MessageProperties();
  props.setHeader("X-B3-TraceId", TRACE_ID);
  props.setHeader("X-B3-SpanId", SPAN_ID);
  props.setHeader("X-B3-ParentSpanId", PARENT_ID);
  props.setHeader("X-B3-Sampled", SAMPLED);

  Message message = MessageBuilder.withBody(new byte[0]).andProperties(props).build();
  onMessageConsumed(message);

  // cleared the headers to later work doesn't try to use the old parent
  assertThat(message.getMessageProperties().getHeaders()).isEmpty();

  assertThat(spans)
    .filteredOn(span -> span.kind() == CONSUMER)
    .extracting(MutableSpan::parentId)
    .contains(SPAN_ID);
}
 
Example 16
@Test
@Description("Tests a invalid message without event topic")
public void invalidEventTopic() {
    final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
    final Message message = new Message(new byte[0], messageProperties);

    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "due to unknown message type").isThrownBy(
                    () -> amqpMessageHandlerService.onMessage(message, "unknownMessageType", TENANT, VIRTUAL_HOST));

    messageProperties.setHeader(MessageHeaderKey.TOPIC, "wrongTopic");
    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "due to unknown topic").isThrownBy(() -> amqpMessageHandlerService
                    .onMessage(message, MessageType.EVENT.name(), TENANT, VIRTUAL_HOST));

    messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.CANCEL_DOWNLOAD.name());
    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "because there was no event topic")
            .isThrownBy(() -> amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT,
                    VIRTUAL_HOST));
}
 
Example 17
@Test
@Description("Tests the update of an action of a target without a exist action id")
public void updateActionStatusWithoutExistActionId() {
    final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
    messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
    when(controllerManagementMock.findActionWithDetails(anyLong())).thenReturn(Optional.empty());

    final DmfActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(DmfActionStatus.DOWNLOAD);
    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
            messageProperties);

    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "since no action id was set")
            .isThrownBy(() -> amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT,
                    VIRTUAL_HOST));
}
 
Example 18
Source Project: SpringBootLearn   Source File: MqSender.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Header模式 交换机Exchange
 *"header1","value1"要与队列初始化的时候一样
 */
public void sendHeaders(Object message){
    logger.info("send headers message: " + message);
    MessageProperties properties = new MessageProperties();
    properties.setHeader("header1","value1");
    properties.setHeader("header2","value2");
    Message obj = new Message(message.toString().getBytes(),properties);
    amqpTemplate.convertAndSend(MqConfig.HEADERS_EXCHANGE,"",obj);
}
 
Example 19
Source Project: Spring-Boot-Book   Source File: MQTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void send() {
    Message message = MessageBuilder.withBody("body content".getBytes())
            .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
            .setMessageId("1")
            .setHeader("header", "header")
            .build();
    amqpTemplate.send("Queue1", message);
    amqpTemplate.convertAndSend("Queue1", "body content");

}
 
Example 20
Source Project: easy-rabbitmq   Source File: CustomMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Message createMessage(Object object, MessageProperties props) {
  byte[] bytes = null;
  if (object instanceof byte[]) {
    bytes = (byte[]) object;
    props.setContentType(MessageProperties.CONTENT_TYPE_BYTES);
  } else if (object instanceof Serializable) {
    bytes = JSON.toJSONBytes(object);
    props.setContentType(MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT);
  }
  if (bytes != null) {
    props.setContentLength(bytes.length);
  }
  return new Message(bytes, props);
}
 
Example 21
Source Project: easy-rabbitmq   Source File: Receiver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, Channel channel) throws Exception {
  try {
    MessageProperties prop = message.getMessageProperties();
    ConsumerDef consumer = ConsumerDef.lookup(prop.getConsumerQueue(), prop.getReceivedExchange(),
        prop.getReceivedRoutingKey());
    if (consumer == null) {
      log.error("consumer not found {}", prop);
      channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
      return;
    }
    Object msg = converter.fromMessage(message);
    if (converter instanceof CustomMessageConverter && msg instanceof byte[]) {
      // 特殊处理
      Type type = consumer.getType();
      if (type != byte[].class) {
        msg = JSON.parseObject((byte[]) msg, type);
      }
    }
    if (log.isDebugEnabled()) {
      log.debug("receive msg {}", msg);
    }
    consumer.accept(msg);
    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
  } catch (Exception e) {
    log.error("receive msg error {}", message, e);
    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
  }
}
 
Example 22
Source Project: iot-dc   Source File: MQSender.java    License: Apache License 2.0 5 votes vote down vote up
public void send(EMqExchange[] mqExchange, String content) {
    Message message = MessageBuilder.withBody(content.getBytes())
            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
            .setContentEncoding("utf-8")
            .build();
    if (mqExchange == null || mqExchange.length == 0) {
        return;
    }
    Arrays.asList(mqExchange).stream().forEach(eMqExchange -> {
        LOGGER.info("send -> {} -> {}", eMqExchange.name(), message);
        this.rabbitTemplate.convertAndSend(eMqExchange.getMqFanoutExchange(), "", message);
    });
}
 
Example 23
public void sendOrder(Order order) {
  rabbit.convertAndSend("tacocloud.order.queue", order,
      new MessagePostProcessor() {
        @Override
        public Message postProcessMessage(Message message)
            throws AmqpException {
          MessageProperties props = message.getMessageProperties();
          props.setHeader("X_ORDER_SOURCE", "WEB");
          return message;
        } 
      });
}
 
Example 24
Source Project: zxl   Source File: SpringMessageConverterAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public <T> Message toReplyMessage(T object, String correlationId) {
	MessageProperties messageProperties = new MessageProperties();
	try {
		messageProperties.setCorrelationId(correlationId.getBytes(DEFAULT_CHARSET));
	} catch (UnsupportedEncodingException e) {}
	return messageConverter.toMessage(object, messageProperties);
}
 
Example 25
public void sendOrder(Order order) {
  rabbit.convertAndSend("tacocloud.order.queue", order,
      new MessagePostProcessor() {
        @Override
        public Message postProcessMessage(Message message)
            throws AmqpException {
          MessageProperties props = message.getMessageProperties();
          props.setHeader("X_ORDER_SOURCE", "WEB");
          return message;
        } 
      });
}
 
Example 26
private Message convertMessageIfNecessary(final Object object) {
  if (object instanceof Message) {
    return (Message) object;
  }

  return messageConverter.toMessage(object, new MessageProperties());
}
 
Example 27
public void onReceive(MessageProperties messageProperties, Span span) {
  Tags.COMPONENT.set(span, RabbitMqTracingTags.RABBITMQ.getKey());
  RabbitMqTracingTags.EXCHANGE.set(span, messageProperties.getReceivedExchange());
  RabbitMqTracingTags.MESSAGE_ID.set(span, messageProperties.getMessageId());
  RabbitMqTracingTags.ROUTING_KEY.set(span, messageProperties.getReceivedRoutingKey());
  RabbitMqTracingTags.CONSUMER_QUEUE.set(span, messageProperties.getConsumerQueue());
}
 
Example 28
Source Project: brave   Source File: TracingRabbitListenerAdvice.java    License: Apache License 2.0 5 votes vote down vote up
void setConsumerSpan(Span span, MessageProperties properties) {
  span.name("next-message").kind(CONSUMER);
  maybeTag(span, RABBIT_EXCHANGE, properties.getReceivedExchange());
  maybeTag(span, RABBIT_ROUTING_KEY, properties.getReceivedRoutingKey());
  maybeTag(span, RABBIT_QUEUE, properties.getConsumerQueue());
  if (remoteServiceName != null) span.remoteServiceName(remoteServiceName);
}
 
Example 29
Source Project: java-spring-rabbitmq   Source File: RabbitMqTracingUtils.java    License: Apache License 2.0 5 votes vote down vote up
static Optional<Scope> buildReceiveSpan(MessageProperties messageProperties, Tracer tracer) {
  Optional<SpanContext> context = findParent(messageProperties, tracer);
  Tracer.SpanBuilder spanBuilder =
      tracer
          .buildSpan(RabbitMqTracingTags.SPAN_KIND_CONSUMER)
          .ignoreActiveSpan()
          .withTag(Tags.SPAN_KIND.getKey(), RabbitMqTracingTags.SPAN_KIND_CONSUMER);

  context.ifPresent(spanContext -> spanBuilder.addReference(References.FOLLOWS_FROM, spanContext));
  Scope scope = tracer.scopeManager().activate(spanBuilder.start());

  return Optional.of(scope);
}
 
Example 30
Source Project: java-spring-rabbitmq   Source File: RabbitMqTracingUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Optional<SpanContext> findParent(
    MessageProperties messageProperties, Tracer tracer) {
  final Map<String, Object> headers = messageProperties.getHeaders();
  SpanContext spanContext =
      tracer.extract(
          Format.Builtin.TEXT_MAP, new RabbitMqMessagePropertiesExtractAdapter(headers));

  if (spanContext == null) {
    return Optional.ofNullable(tracer.activeSpan()).map(Span::context);
  } else {
    return Optional.of(spanContext);
  }
}