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

The following examples show how to use org.springframework.amqp.core.Message. 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
@Bean
MessageListener exampleListener(final RabbitTemplate rabbitTemplate) {
	return new MessageListener() {
		public void onMessage(Message message) {
			System.out.println("received: " + message);
			try {
				String payload = new ObjectMapper().writeValueAsString(new MyPojo(
						"992e46d8-ab05-4a26-a740-6ef7b0daeab3", "CREATED"));
				Message outputMessage = MessageBuilder.withBody(payload.getBytes())
						.build();
				rabbitTemplate.send(issue178OutputExchange().getName(), "routingkey",
						outputMessage);
			}
			catch (JsonProcessingException e) {
				throw new RuntimeException(e);
			}
		}
	};
}
 
Example 2
@Test
public void convertAndSend_withRoutingKeyAndMessagePostProcessor_shouldBeTraced() {
  // given
  Message requestMessage = createMessage();
  MessagePostProcessor messagePostProcessor = msg -> msg;

  // when
  rabbitTemplate.convertAndSend(ROUTING_KEY, requestMessage, messagePostProcessor);

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

  assertOnSpans(sentSpan, receiveSpan, ROUTING_KEY);
}
 
Example 3
Source Project: zxl   Source File: AbstractMqMessageConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T fromMessage(Message message, String className) {
	if (message == null) {
		return null;
	}
	if (Message.class.getName().equals(className)) {
		return (T) message;
	}
	try {
		return (T) fromMessage(message, className == null ? null : getClass().getClassLoader().loadClass(className));
	} catch (Exception warnException) {
		LogUtil.warn(logger, "#####��Ϣת��ʧ��", warnException);
		return null;
	}
}
 
Example 4
@Test
@Description("Verify that the receive message contains a 200 code and a artifact for the existing target id ")
public void artifactForFileResourceSHA1FoundByTargetIdTargetExistsIsAssigned() {
    final Target target = createTarget(TARGET);

    final DistributionSet distributionSet = createDistributionSet();
    final List<Artifact> artifacts = createArtifacts(distributionSet);
    final Artifact artifact = artifacts.get(0);
    final DmfTenantSecurityToken securityToken = createTenantSecurityToken(TENANT_EXIST, target.getId(), null,
            FileResource.createFileResourceBySha1(artifact.getSha1Hash()));

    assignDistributionSet(distributionSet.getId(), TARGET);

    final Message returnMessage = sendAndReceiveAuthenticationMessage(securityToken);
    verifyOkResult(returnMessage, artifact);

}
 
Example 5
Source Project: bird-java   Source File: RabbitEventArgListener.java    License: MIT License 6 votes vote down vote up
@Override
public void onMessage(Message message, Channel channel) throws Exception {
    Class<?> clazz;
    String className = message.getMessageProperties().getReceivedExchange();
    try {
        clazz = Class.forName(className);
        if (!IEventArg.class.isAssignableFrom(clazz)) {
            log.error("事件处理失败:" + className + "不是IEventArg的子类");
        }
    } catch (ClassNotFoundException ex) {
        log.error("事件处理失败:", ex);
        return;
    }

    String body = new String(message.getBody(), Charset.forName("utf8"));
    IEventArg eventArg = (IEventArg) JSON.parseObject(body,clazz);

    dispatcher.enqueue(eventArg);
    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
}
 
Example 6
Source Project: HIS   Source File: RabbitMQOrderSender.java    License: Apache License 2.0 6 votes vote down vote up
public void sendMessage(Long orderId,int type,final long delayTimes){
    //发送信息格式:id&类型(1检查\检验\处置 4草药 5成药)
    String msg = orderId + "&" + type;
    //给延迟队列发送消息
    amqpTemplate.convertAndSend(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange(),
                                QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey(),
                                msg,
            new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    //给消息设置延迟毫秒值
                     message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
                     return message;
             }
    });
    LOGGER.info("send order message msg:{}",msg);
}
 
Example 7
Source Project: seed   Source File: ReceiveService.java    License: Apache License 2.0 6 votes vote down vote up
@RabbitListener(queues="${spring.rabbitmq.queues}", containerFactory="jadyerRabbitListenerContainerFactory")
public void receive(UserMsg userMsg, Channel channel, Message message){
    try {
        LogUtil.getLogger().info("收到消息-->[{}]", ReflectionToStringBuilder.toString(userMsg));
        //确认消费成功(第一个参数:消息编号。第二个参数:是否确认多条消息,false为确认当前消息,true为确认deliveryTag编号以前的所有消息)
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }catch(Exception e){
        LogUtil.getLogger().error("消息处理异常,消息ID={}, 消息体=[{}]", message.getMessageProperties().getCorrelationId(), JSON.toJSONString(userMsg), e);
        try {
            //拒绝当前消息,并把消息返回原队列(第三个参数:是否将消息放回队列,true表示放回队列,false表示丢弃消息)
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            //basicReject只能拒绝一条消息,而basicNack能够拒绝多条消息
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e1) {
            LogUtil.getLogger().error("消息basicNack时发生异常,消息ID={}", message.getMessageProperties().getCorrelationId(), e);
        }
    }
}
 
Example 8
Source Project: spring-boot-demo   Source File: QueueTwoHandler.java    License: MIT License 6 votes vote down vote up
@RabbitHandler
public void directHandlerManualAck(MessageStruct messageStruct, Message message, Channel channel) {
    //  如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果 未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉
    final long deliveryTag = message.getMessageProperties().getDeliveryTag();
    try {
        log.info("队列2,手动ACK,接收消息:{}", JSONUtil.toJsonStr(messageStruct));
        // 通知 MQ 消息已被成功消费,可以ACK了
        channel.basicAck(deliveryTag, false);
    } catch (IOException e) {
        try {
            // 处理失败,重新压入MQ
            channel.basicRecover();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
 
Example 9
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 10
Source Project: iot-dc   Source File: MqListener.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 指令队列
 *
 * @param message
 */
@RabbitListener(queues = "rtu_inst_queue")
@RabbitHandler
public void command(Message message) throws IOException {
    String msg = new String(message.getBody());
    LOGGER.info("rtu-command: {}", msg);
    RTUCommandInfo commandInfo = JsonUtils.jsonStr2Obj(msg, RTUCommandInfo.class);
    if (commandInfo == null ||
            StringUtils.isEmpty(commandInfo.getSn()) ||
            StringUtils.isEmpty(commandInfo.getInstruction()) ||
            StringUtils.isEmpty(commandInfo.getInstructionType())) {
        LOGGER.warn("bad command: {}", commandInfo);
        return;
    }
    CommandHandler.writeCommand(commandInfo.getSn(), commandInfo.getInstruction(), commandInfo.getInstructionType());
}
 
Example 11
Source Project: heimdall   Source File: MiddlewareListener.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Updates the {@link Middleware} repository.
 * 
 * @param message {@link Message}
 */
@RabbitListener(queues = RabbitConstants.LISTENER_HEIMDALL_MIDDLEWARES)
public void updateMiddlewares(final Message message) {
     
     try {
          Long middlewareId = (Long) rabbitTemplate.getMessageConverter().fromMessage(message);

          Middleware middleware = middlewareRepository.findOne(middlewareId);
          if (middleware != null) {
               
               log.info("Updating/Creating middleware id: " + middlewareId);
               startServer.addApiDirectoryToPath(middleware.getApi());
               startServer.createMiddlewaresInterceptor(middleware);
               startServer.loadMiddlewareFiles(middleware);
          } else {
               
               log.info("It was not possible Updating/Creating middleware id: " + middlewareId);
          }
     } catch (Exception e) {
          log.error(e.getMessage(), e);
     }
     
}
 
Example 12
@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 13
@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 14
@Test
public void convertSendAndReceive_withMessageAndMessagePostProcessor_shouldBeTraced() {
  // given
  Message requestMessage = createMessage();
  MessagePostProcessor messagePostProcessor = msg -> msg;

  // when
  Object response = rabbitTemplate.convertSendAndReceive(requestMessage, messagePostProcessor);

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

  assertOnSpans(sentSpan, receiveSpan, EMPTY_ROUTING_KEY);
}
 
Example 15
@Test
public void sendAndReceive_withProcessedLongerThanRabbitTemplateTimeout_shouldProduceSpanWithError() {
  // given
  Message requestMessage = createMessage();
  requestMessage.getMessageProperties().setHeader(TestMessageListener.HEADER_SLEEP_MILLIS,
      RabbitWithRabbitTemplateConfig.RABBIT_TEMPLATE_REPLY_TIMEOUT_MILLIS + 500);

  // when
  Message response = rabbitTemplate.sendAndReceive(EXCHANGE, ROUTING_KEY, requestMessage, null);

  // then
  assertThat(response, nullValue()); // response is null in case of timeout

  List<MockSpan> nowFinishedSpans = tracer.finishedSpans();
  assertThat(nowFinishedSpans.size(), equalTo(1)); // only send span should be finished, consumer is still sleeping

  MockSpan sendSpan = nowFinishedSpans.get(0);
  assertSpanRabbitTags(sendSpan, RabbitMqTracingTags.SPAN_KIND_PRODUCER, ROUTING_KEY);

  assertErrorTag(sendSpan); // check that when response wasn't sent before timeout,
  // then error tag is added (so span of the trace could be highlighted in UI)

  MockSpan receiveSpan = awaitFinishedSpans().getReceiveSpan();
  assertThat(REASON, receiveSpan, notNullValue());
  assertRabbitConsumerSpan(receiveSpan, ROUTING_KEY);
}
 
Example 16
@Test
public void convertSendAndReceive_withRoutingKeyMessageAndMessagePostProcessor_shouldBeTraced() {
  // given
  Message requestMessage = createMessage();
  MessagePostProcessor messagePostProcessor = msg -> msg;

  // when
  Object response = rabbitTemplate.convertSendAndReceive(ROUTING_KEY, requestMessage, messagePostProcessor);

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

  assertOnSpans(sentSpan, receiveSpan, ROUTING_KEY);
}
 
Example 17
@Test
public void shouldReceiveOnConfigPub() throws Exception {

    final String apiKey = "jV5bnJWK";
    final String channel = "temp";
    final String payload = "{ 'a' : '52T' }";
    final Long epochMilli = 1490001001000L;
    Instant timestamp = Instant.ofEpochMilli(epochMilli);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setHeader("apiKey", apiKey);
    messageProperties.setHeader("channel", channel);
    messageProperties.setHeader("ts", epochMilli);

    Message message = new Message(payload.getBytes("UTF-8"), messageProperties);
    deviceEventRabbitEndpoint.onDataPub(message);

    verify(deviceEventProcessor, times(1)).process(apiKey, channel, payload.getBytes("UTF-8"), timestamp);

}
 
Example 18
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 19
Source Project: heimdall   Source File: InterceptorListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Removes a {@link Interceptor}.
 * 
 * @param message {@link Message}
 */
@RabbitListener(queues = RabbitConstants.LISTENER_HEIMDALL_REMOVE_INTERCEPTORS)
public void removeInterceptor(final Message message) {
     
     InterceptorFileDTO interceptor = (InterceptorFileDTO) rabbitTemplate.getMessageConverter().fromMessage(message);
     log.info("Removing Interceptor id: " + interceptor.getId());
     
     interceptorFileService.removeFileInterceptor(interceptor);
}
 
Example 20
Source Project: hawkbit   Source File: AmqpMessageHandlerService.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void updateAttributes(final Message message) {
    final DmfAttributeUpdate attributeUpdate = convertMessage(message, DmfAttributeUpdate.class);
    final String thingId = getStringHeaderKey(message, MessageHeaderKey.THING_ID, THING_ID_NULL);

    controllerManagement.updateControllerAttributes(thingId, attributeUpdate.getAttributes(),
            getUpdateMode(attributeUpdate));
}
 
Example 21
@Test
@Description("Verify that the receive message contains a 404, if there is no distribution set assigned to the target")
public void artifactForFileResourceFileNameFoundTargetExistsButNotAssigned() {
    createTarget(TARGET);

    final DistributionSet distributionSet = createDistributionSet();
    final List<Artifact> artifacts = createArtifacts(distributionSet);
    final DmfTenantSecurityToken securityToken = createTenantSecurityToken(TENANT_EXIST, TARGET,
            FileResource.createFileResourceByFilename(artifacts.get(0).getFilename()));

    final Message returnMessage = sendAndReceiveAuthenticationMessage(securityToken);
    verifyResult(returnMessage, HttpStatus.NOT_FOUND,
            "Artifact for resource FileResource [sha1=null, artifactId=null, filename=filename0] not found ");

}
 
Example 22
private void assertLatestMultiActionMessageContainsInstallMessages(final String controllerId,
        final List<Set<Long>> smIdsOfActionsExpected) {
    final Message multiactionMessage = replyToListener.getLatestEventMessage(EventTopic.MULTI_ACTION);
    assertThat(multiactionMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.THING_ID))
            .isEqualTo(controllerId);
    final DmfMultiActionRequest multiActionRequest = (DmfMultiActionRequest) getDmfClient().getMessageConverter()
            .fromMessage(multiactionMessage);

    final List<Set<Long>> smIdsOfActionsFound = getDownloadAndUpdateRequests(multiActionRequest).stream()
            .map(AmqpMessageDispatcherServiceIntegrationTest::getSmIds).collect(Collectors.toList());
    assertThat(smIdsOfActionsFound).containsExactlyInAnyOrderElementsOf(smIdsOfActionsExpected);
}
 
Example 23
@Test
@Description("Verify that the receive message contains a 404 code,if the artifact could not found")
public void fileResourceGetSha1InSecurityTokenIsNull() {
    enableAnonymousAuthentication();
    final DmfTenantSecurityToken securityToken = createTenantSecurityToken(TENANT_EXIST, TARGET,
            FileResource.createFileResourceBySha1(null));

    final Message returnMessage = sendAndReceiveAuthenticationMessage(securityToken);
    verifyResult(returnMessage, HttpStatus.NOT_FOUND,
            "Artifact for resource FileResource [sha1=null, artifactId=null, filename=null] not found ");

}
 
Example 24
@Test
public void convertSendAndReceive_withMessageAndMessagePostProcessor_shouldBeTraced() {
  // given
  Message requestMessage = createMessage();
  MessagePostProcessor messagePostProcessor = msg -> msg;

  // when
  Object response = rabbitTemplate.convertSendAndReceive(requestMessage, messagePostProcessor);

  // then
  assertConsumerAndProducerSpans(0, EMPTY_ROUTING_KEY);
  assertOnResponse(response);
}
 
Example 25
@Test
@Description("Verify that the receive message contains a 200 code and a artifact without a controller id (anonymous enabled)")
public void anonymousAuthentification() {
    enableAnonymousAuthentication();
    final DistributionSet distributionSet = createDistributionSet();
    final List<Artifact> artifacts = createArtifacts(distributionSet);
    final Artifact artifact = artifacts.get(0);
    final DmfTenantSecurityToken securityToken = createTenantSecurityToken(TENANT_EXIST, null, null,
            FileResource.createFileResourceBySha1(artifact.getSha1Hash()));

    final Message returnMessage = sendAndReceiveAuthenticationMessage(securityToken);
    verifyOkResult(returnMessage, artifact);

}
 
Example 26
@Test
@Description("Tests that an download request is allowed for an artifact which exists and assigned to the requested target")
public void authenticationRequestAllowedForArtifactWhichExistsAndAssignedToTarget() throws MalformedURLException {
    final MessageProperties messageProperties = createMessageProperties(null);
    final DmfTenantSecurityToken securityToken = new DmfTenantSecurityToken(TENANT, TENANT_ID, CONTROLLER_ID,
            TARGET_ID, FileResource.createFileResourceBySha1("12345"));
    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
            messageProperties);

    // mock
    final Artifact localArtifactMock = mock(Artifact.class);
    when(localArtifactMock.getSha1Hash()).thenReturn(SHA1);
    when(localArtifactMock.getMd5Hash()).thenReturn("md5");
    when(localArtifactMock.getSize()).thenReturn(1L);

    when(artifactManagementMock.findFirstBySHA1(SHA1)).thenReturn(Optional.of(localArtifactMock));
    when(controllerManagementMock.hasTargetArtifactAssigned(securityToken.getControllerId(), SHA1))
            .thenReturn(true);
    when(hostnameResolverMock.resolveHostname()).thenReturn(new URL("http://localhost"));

    // test
    final Message onMessage = amqpAuthenticationMessageHandlerService.onAuthenticationRequest(message);

    // verify
    final DmfDownloadResponse downloadResponse = (DmfDownloadResponse) messageConverter.fromMessage(onMessage);
    assertThat(downloadResponse).as("Message body should not null").isNotNull();
    assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong")
            .isEqualTo(HttpStatus.OK.value());
    assertThat(downloadResponse.getArtifact().getSize()).as("Wrong artifact size in message body").isEqualTo(1L);
    assertThat(downloadResponse.getArtifact().getHashes().getSha1()).as("Wrong sha1 hash").isEqualTo(SHA1);
    assertThat(downloadResponse.getArtifact().getHashes().getMd5()).as("Wrong md5 hash").isEqualTo("md5");
    assertThat(downloadResponse.getDownloadUrl()).as("download url is wrong")
            .startsWith("http://localhost/api/v1/downloadserver/downloadId/");
}
 
Example 27
Source Project: brave   Source File: SpringRabbitTracing.java    License: 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 28
@Test
@Description("Tests authentication message successfull with targetId intead of controllerId provided and artifactId instead of SHA1.")
public void successfullMessageAuthenticationWithTargetIdAndArtifactId() {
    final MessageProperties messageProperties = createMessageProperties(null);
    final DmfTenantSecurityToken securityToken = new DmfTenantSecurityToken(TENANT, null, null, TARGET_ID,
            FileResource.createFileResourceByArtifactId(ARTIFACT_ID));
    when(tenantConfigurationManagementMock.getConfigurationValue(
            eq(TenantConfigurationKey.AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED), eq(Boolean.class)))
                    .thenReturn(CONFIG_VALUE_TRUE);
    securityToken.putHeader(DmfTenantSecurityToken.AUTHORIZATION_HEADER, "TargetToken " + CONTROLLER_ID);
    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
            messageProperties);

    // test
    final Message onMessage = amqpAuthenticationMessageHandlerService.onAuthenticationRequest(message);

    // verify
    final DmfDownloadResponse downloadResponse = (DmfDownloadResponse) messageConverter.fromMessage(onMessage);
    assertThat(downloadResponse).isNotNull();
    assertThat(downloadResponse.getDownloadUrl()).isNotNull();
    assertThat(downloadResponse.getResponseCode()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext()).isNotNull();
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
    assertThat(SecurityContextHolder.getContext().getAuthentication().getClass().getName())
            .isEqualTo(PreAuthenticatedAuthenticationToken.class.getName());

}
 
Example 29
Source Project: brave   Source File: MessageHeaders.java    License: 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 30
@Test
public void sendAndReceive_withoutExchangeAndRoutingKey_shouldNotBeTraced() {
  // given
  Message requestMessage = createMessage();

  // when
  Message response = rabbitTemplate.sendAndReceive(requestMessage);

  // then
  checkNoSpans();
}