Java Code Examples for org.springframework.amqp.core.Message#getMessageProperties()

The following examples show how to use org.springframework.amqp.core.Message#getMessageProperties() . 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: RabbitWithoutRabbitTemplateConfig.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
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 2
Source File: RabbitMqSendTracingHelper.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
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 3
Source File: RabbitMqReceiveTracingInterceptor.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  Message message = (Message) methodInvocation.getArguments()[1];
  MessageProperties messageProperties = message.getMessageProperties();

  Optional<Scope> child = RabbitMqTracingUtils.buildReceiveSpan(messageProperties, tracer);
  child.ifPresent(scope -> spanDecorator.onReceive(messageProperties, tracer.scopeManager().activeSpan()));

  // CHECKSTYLE:OFF
  try {
    return methodInvocation.proceed();
  } catch (Exception ex) {
    // CHECKSTYLE:ON
    child.ifPresent(scope -> spanDecorator.onError(ex, tracer.scopeManager().activeSpan()));
    throw ex;
  } finally {
    child.ifPresent(it -> {
      Optional.ofNullable(tracer.scopeManager().activeSpan())
          .ifPresent(Span::finish);
      it.close();
    });
  }
}
 
Example 4
Source File: SpringRabbitMQAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void onMessageEnter(final Object msg) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder builder = tracer
    .buildSpan("onMessage")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER);

  final Message message = (Message)msg;
  if (message.getMessageProperties() != null) {
    final Map<String,Object> headers = message.getMessageProperties().getHeaders();
    final SpanContext spanContext = tracer.extract(Builtin.TEXT_MAP, new HeadersMapExtractAdapter(headers));
    if (spanContext != null)
      builder.addReference(References.FOLLOWS_FROM, spanContext);
  }

  final Span span = builder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example 5
Source File: MQServer.java    From zxl with 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 6
Source File: RabbitChannelMessageListenerAdapter.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(Message message) {
    byte[] body = message.getBody();
    MessageProperties messageProperties = message.getMessageProperties();
    String contentType = messageProperties != null ? messageProperties.getContentType() : null;

    String rawEvent;
    if (body == null) {
        rawEvent = null;
    } else if (stringContentTypes.contains(contentType)) {
        rawEvent = new String(body, StandardCharsets.UTF_8);
    } else {
        rawEvent = Base64.getEncoder().encodeToString(body);
    }

    eventRegistry.eventReceived(inboundChannelModel, rawEvent);
}
 
Example 7
Source File: DmfReceiverService.java    From hawkbit-examples with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Method to validate if content type is set in the message properties.
 *
 * @param message
 *            the message to get validated
 */
private void checkContentTypeJson(final Message message) {
    if (message.getBody().length == 0) {
        return;
    }
    final MessageProperties messageProperties = message.getMessageProperties();
    final String headerContentType = (String) messageProperties.getHeaders().get("content-type");
    if (null != headerContentType) {
        messageProperties.setContentType(headerContentType);
    }
    final String contentType = messageProperties.getContentType();
    if (contentType != null && contentType.contains("json")) {
        return;
    }
    throw new AmqpRejectAndDontRequeueException("Content-Type is not JSON compatible");
}
 
Example 8
Source File: SpringRabbitTracing.java    From brave with Apache License 2.0 5 votes vote down vote up
<R> TraceContextOrSamplingFlags extractAndClearTraceIdHeaders(
  Extractor<R> extractor, R request, Message message
) {
  TraceContextOrSamplingFlags extracted = extractor.extract(request);
  // Clear any propagation keys present in the headers
  if (extracted.samplingFlags() == null) { // then trace IDs were extracted
    MessageProperties properties = message.getMessageProperties();
    if (properties != null) clearTraceIdHeaders(properties.getHeaders());
  }
  return extracted;
}
 
Example 9
Source File: Receiver.java    From easy-rabbitmq with 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 10
Source File: MessageHeaders.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * If {@link MessageProperties} exist, this returns {@link MessageProperties#getHeader(String)} if
 * it is a string.
 */
@Nullable static String getHeaderIfString(Message message, String name) {
  MessageProperties properties = message.getMessageProperties();
  if (properties == null) return null;
  Object o = properties.getHeader(name);
  if (o instanceof String) return o.toString();
  return null;
}
 
Example 11
Source File: BaseAmqpService.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
protected static void checkContentTypeJson(final Message message) {
    final MessageProperties messageProperties = message.getMessageProperties();
    if (messageProperties.getContentType() != null && messageProperties.getContentType().contains("json")) {
        return;
    }
    throw new AmqpRejectAndDontRequeueException("Content-Type is not JSON compatible");
}
 
Example 12
Source File: DeviceConfigRabbitEndpoint.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@RabbitListener(queues = "mgmt.config.pub")
  public void onConfigPub(Message message) {

      if (LOGGER.isDebugEnabled())
          LOGGER.debug("A message has arrived -> " + message);

      MessageProperties properties = message.getMessageProperties();
      if (properties == null || properties.getHeaders().isEmpty()) {
          LOGGER.error("MessageProperties is empty");
          return;
      }

      String apiKey = (String) properties.getHeaders().get(RabbitMQDataConfig.MSG_HEADER_APIKEY);
      if (!StringUtils.hasText(apiKey)) {
          LOGGER.error("Apikey not found.");
          return;
      }

Device device = deviceRegisterService.findByApiKey(apiKey);

      if (!Optional.ofNullable(device).isPresent()) {
          LOGGER.error("Device does not exist");
          return;
      }

      ServiceResponse<String> serviceResponse = deviceConfigSetupService
      		.findByModelAndLocation(device.getTenant(),
      				device.getApplication(),
      				device.getDeviceModel(),
      				device.getLocation());

      String config = Optional.ofNullable(serviceResponse.getResult()).orElse("{ }");

      rabbitGateway.sendConfig(apiKey, config);

  }
 
Example 13
Source File: RabbitMqReceiveTracingInterceptorTest.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
private Message getMessageWithContext() {
  Message message = getMessage();
  MessageProperties messageProperties = message.getMessageProperties();
  messageProperties.setHeader("traceid", 1L);
  messageProperties.setHeader("spanid", 1L);
  return new Message("".getBytes(Charset.defaultCharset()), messageProperties);
}
 
Example 14
Source File: RepublishMessageRecovererExtend.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private String createRetryQueueAndGetRetryRourtingKey(Message message) {
    MessageProperties messageProperties = message.getMessageProperties();
    String exchange = messageProperties.getReceivedExchange();
    String routeKey = messageProperties.getReceivedRoutingKey();
    String queueName = messageProperties.getConsumerQueue();
    String retryQueueName = queueName + DeadLetterConstant.DEFAULT_RETRY_QUEUENAME_PREFIX;
    String retryRouteKey = routeKey + DeadLetterConstant.DEFAULT_RETRY_QUEUENAME_PREFIX;
    deadLetterQueueCreator.createDeadLetterQueue(exchange, routeKey, retryRouteKey, queueName, retryQueueName,
        interval);
    return retryRouteKey;
}
 
Example 15
Source File: DmfReceiverService.java    From hawkbit-examples with Eclipse Public License 1.0 4 votes vote down vote up
private static String getTenant(final Message message) {
    final MessageProperties messageProperties = message.getMessageProperties();
    final Map<String, Object> headers = messageProperties.getHeaders();
    return (String) headers.get(MessageHeaderKey.TENANT);
}
 
Example 16
Source File: DeviceEventRabbitEndpoint.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@RabbitListener(queues = "data.pub")
public void onDataPub(Message message) {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("A message has arrived -> " + message);

    MessageProperties properties = message.getMessageProperties();
    if (properties == null || properties.getHeaders().isEmpty()) {
        LOGGER.error("MessageProperties is empty");
        return;
    }

    String apiKey = (String) properties.getHeaders().get(RabbitMQDataConfig.MSG_HEADER_APIKEY);
    String channel = (String) properties.getHeaders().get(RabbitMQDataConfig.MSG_HEADER_CHANNEL);
    Long epochMilli = (Long) properties.getHeaders().get(RabbitMQDataConfig.MSG_HEADER_TIMESTAMP);
    Instant ingestedTimestamp = null;

    byte[] bytesPayload = message.getBody();

    if (!StringUtils.hasText(apiKey)) {
        LOGGER.error("Apikey not found.");
        return;
    }
    if (!StringUtils.hasText(channel)) {
        LOGGER.error("Channel not found.");
        return;
    }
    if (epochMilli != null) {
        ingestedTimestamp = Instant.ofEpochMilli(epochMilli);
    } else {
    	LOGGER.error("ts rabbit not found.");
    	ingestedTimestamp = Instant.now();
    }

    try {
        deviceEventProcessor.process(apiKey, channel, bytesPayload, ingestedTimestamp);
    } catch (BusinessException | JsonProcessingException be) {
        LOGGER.error("BusinessException processing message", be);
    }

}
 
Example 17
Source File: RabbitConfiguration.java    From tutorials with MIT License 4 votes vote down vote up
@RabbitListener(queues = "retry-wait-ended-queue", containerFactory = "defaultContainerFactory")
public void consumeRetryWaitEndedMessage(String payload, Message message, Channel channel) throws Exception {
    MessageProperties props = message.getMessageProperties();

    rabbitTemplate().convertAndSend(props.getHeader("x-original-exchange"), props.getHeader("x-original-routing-key"), message);
}
 
Example 18
Source File: MessageHeaders.java    From brave with Apache License 2.0 4 votes vote down vote up
/**
 * If {@link MessageProperties} exist, this invokes {@link MessageProperties#setHeader(String,
 * Object)}.
 */
static void setHeader(Message message, String name, String value) {
  MessageProperties properties = message.getMessageProperties();
  if (properties == null) return;
  properties.setHeader(name, value);
}