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

The following examples show how to use org.springframework.amqp.core.Message#getBody() . 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: AsyncRPCServer.java    From SpringBootBucket with MIT License 6 votes vote down vote up
@RabbitListener(queues = QUEUE_ASYNC_RPC)
public void processAsyncRpc(Message message, @Header(AmqpHeaders.REPLY_TO) String replyTo) {
    String body = new String(message.getBody(), Charset.forName("UTF-8"));
 User user = JacksonUtil.json2Bean(body, new TypeReference<User>(){});
    logger.info("recevie message {} and reply to {}, user.name={}", body, replyTo, user.getName());
    if (replyTo.startsWith("amq.rabbitmq.reply-to")) {
        logger.debug("starting with version 3.4.0, the RabbitMQ server now supports Direct reply-to");
    } else {
        logger.info("fall back to using a temporary reply queue");
    }
    ListenableFuture<String> asyncResult = asyncTask.expensiveOperation(body);
    asyncResult.addCallback(new ListenableFutureCallback<String>() {
        @Override
        public void onSuccess(String result) {
            amqpTemplate.convertAndSend(replyTo, result);
        }

        @Override
        public void onFailure(Throwable ex) {
            logger.error("接受到QUEUE_ASYNC_RPC失败", ex);
        }
    });
}
 
Example 2
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 3
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 4
Source File: ESMessageListener.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
public void doWork(Message message) {
    String routingKey = message.getMessageProperties().getReceivedRoutingKey();
    Matcher m = ESConstants.ROUTINGKEY_PATTERN.matcher(routingKey);
    try {
        if (m.find() && m.groupCount() == 3) {
            ESHandleMessage esHandleMessage = new ESHandleMessage(Long.parseLong(m.group(3)),
                    m.group(1), m.group(2), message.getBody());
            esHandleMessage.setEventGenerated(isGeneratedMessage(message));
            handleMsg(esHandleMessage);
        } else {
            lightLogger.warn("Message is invalid: " + routingKey);
        }
    } finally {
        lightLogger.info("Done");
    }

}
 
Example 5
Source File: RabbitEventArgListener.java    From bird-java with 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 File: MqListener.java    From iot-dc with 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 7
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 8
Source File: TestReceiver_Post_1_6_0.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private <T> T convertMessage(MessageConverter<T> messageConverter, Message message) {
    if (message == null) {
        return null;
    }
    byte[] body = message.getBody();
    return messageConverter.convertMessage(body);
}
 
Example 9
Source File: MqListener.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
/**
 * 刷新 iot信息
 *
 * @param message
 * @throws Exception
 */
@RabbitListener(queues = "rtu_refresh_queue")
@RabbitHandler
public void refreshIotInfo(Message message) throws Exception {
    String msg = new String(message.getBody());
    if (GlobalInfo.Global_Iot_Redis_Key.equals(msg)) {
        LOGGER.info("start refresh GlobalInfo, rtu_refresh key is : {}", msg);
        boolean flag = ioTService.refreshIotMapper2Global();
        if (flag) {
            ChannelManagerHandler.refreshRTUChannelInfo();
        }
    }
}
 
Example 10
Source File: LabelStatisticsListener.java    From notes with Apache License 2.0 5 votes vote down vote up
/**
 * 处理传输过来的数据
 * @param message 传送的消息内容
 * @param channel 实现通道
 * @return: void
 * @author: fruiqi
 * @date: 19-2-19 下午2:52
 */
@Override
public void onMessage(Message message, Channel channel) throws Exception {
    String mes = new String(message.getBody());
    logger.info("[INFO] message is {}",mes);

    // 手动应答 消息已消费
    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

}
 
Example 11
Source File: ToUpperCase.java    From cukes with Apache License 2.0 5 votes vote down vote up
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue,
                exchange = @Exchange(value = RabbitMQConfiguration.EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
                key = "upper"
        )
})
public void onMessage(Message message) {
    String text = new String(message.getBody());
    System.out.println("ToUpperCase.onMessage - " + text);
    String result = text.toUpperCase();
    template.convertAndSend(message.getMessageProperties().getReplyTo(), result);
}
 
Example 12
Source File: OrderConsumerMessage.java    From SpringBoot-Course with MIT License 5 votes vote down vote up
@Override
public void onMessage(Message message, Channel channel) throws Exception {
    String msg = new String(message.getBody());

    System.out.println("----------- Message -----------");
    System.out.println(msg);
}
 
Example 13
Source File: TestReceiver_Pre_1_6_0.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T receiveMessage(String queueName, MessageConverter<T> messageConverter) {
    Message message = rabbitTemplate.receive(queueName);
    if (message == null) {
        return null;
    }
    byte[] body = message.getBody();
    return messageConverter.convertMessage(body);
}
 
Example 14
Source File: MqListener.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
/**
 * 刷新 iot信息
 *
 * @param message
 * @throws Exception
 */
@RabbitListener(queues = "rtu_refresh_queue")
@RabbitHandler
public void refreshIotInfo(Message message) throws Exception {
    String msg = new String(message.getBody());
    if (GlobalInfo.Global_Iot_Redis_Key.equals(msg)) {
        LOGGER.info("start refresh GlobalInfo, rtu_refresh key is : {}", msg);
        boolean flag = ioTService.refreshIotMapper2Global();
        if (flag) {
            ChannelManagerHandler.refreshRTUChannelInfo();
        }
    }
}
 
Example 15
Source File: PDFMessageConverter.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public Object fromMessage(Message message) throws MessageConversionException {
	System.err.println("-----------PDF MessageConverter----------");
	
	byte[] body = message.getBody();
	String fileName = UUID.randomUUID().toString();
	String path = "d:/010_test/" + fileName + ".pdf";
	File f = new File(path);
	try {
		Files.copy(new ByteArrayInputStream(body), f.toPath());
	} catch (IOException e) {
		e.printStackTrace();
	}
	return f;
}
 
Example 16
Source File: TextMessageConverter.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public Object fromMessage(Message message) throws MessageConversionException {
	String contentType = message.getMessageProperties().getContentType();
	// testSendMessage4Text
	if(null != contentType && contentType.contains("text")) {
		return new String(message.getBody());
	}
	return message.getBody();
}
 
Example 17
Source File: CustomMessageConverter.java    From easy-rabbitmq with Apache License 2.0 4 votes vote down vote up
@Override
public Object fromMessage(Message message) {
  return message.getBody();
}
 
Example 18
Source File: RabbitMessageChannelBinder.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@Override
public Object fromMessage(Message message) throws MessageConversionException {
	return message.getBody();
}
 
Example 19
Source File: BaseAmqpService.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
protected static boolean isMessageBodyEmpty(final Message message) {
    return message.getBody() == null || message.getBody().length == 0;
}
 
Example 20
Source File: POListener.java    From Spring-MVC-Blueprints with MIT License 3 votes vote down vote up
@Override
public void onMessage(Message message) {
	 String messageBody= new String(message.getBody());
	   // Retrieve the PO
        
	
}