org.springframework.amqp.core.Message Java Examples
The following examples show how to use
org.springframework.amqp.core.Message.
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: RabbitMqTracingAutoConfigurationCustomizationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 10 votes |
@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 #2
Source File: MiddlewareListener.java From heimdall with Apache License 2.0 | 6 votes |
/** * 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 #3
Source File: QueueTwoHandler.java From spring-boot-demo with MIT License | 6 votes |
@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 #4
Source File: ReceiveService.java From seed with Apache License 2.0 | 6 votes |
@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 #5
Source File: RabbitMQOrderSender.java From HIS with Apache License 2.0 | 6 votes |
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 #6
Source File: RabbitEventArgListener.java From bird-java with MIT License | 6 votes |
@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 #7
Source File: MQServer.java From zxl with Apache License 2.0 | 6 votes |
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 #8
Source File: RabbitMqTracingAutoConfigurationCustomizationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 6 votes |
@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 #9
Source File: AmqpAuthenticationMessageHandlerIntegrationTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@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 #10
Source File: RabbitMqTracingAutoConfigurationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 6 votes |
@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 #11
Source File: AbstractMqMessageConverter.java From zxl with Apache License 2.0 | 6 votes |
@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 #12
Source File: RabbitChannelMessageListenerAdapter.java From flowable-engine with Apache License 2.0 | 6 votes |
@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 #13
Source File: RabbitMqTracingAutoConfigurationCustomizationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 6 votes |
@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 #14
Source File: DeviceEventRabbitEndpointTest.java From konker-platform with Apache License 2.0 | 6 votes |
@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 #15
Source File: MqListener.java From iot-dc with Apache License 2.0 | 6 votes |
/** * 指令队列 * * @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 #16
Source File: Issue178ListenerConfiguration.java From spring-cloud-contract with Apache License 2.0 | 6 votes |
@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 #17
Source File: TracingRabbitTemplate.java From java-spring-rabbitmq with Apache License 2.0 | 6 votes |
@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 #18
Source File: RabbitMqTracingNoConfigurationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 5 votes |
@Test public void sendAndReceive_withRoutingKeyAndMessage_shouldNotBeTraced() { // given Message requestMessage = createMessage(); // when rabbitTemplate.sendAndReceive(ROUTING_KEY, requestMessage); // then checkNoSpans(); }
Example #19
Source File: RabbitMqTracingManualConfigurationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 5 votes |
@Test public void send_withRoutingKeyAndWithoutExchange_shouldBeTraced() { // given Message requestMessage = createMessage(); // when rabbitTemplate.send(ROUTING_KEY, requestMessage); // then assertConsumerAndProducerSpans(0, ROUTING_KEY); }
Example #20
Source File: AmqpMessageDispatcherService.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
protected void sendCancelMessageToTarget(final String tenant, final String controllerId, final Long actionId, final URI address) { if (!IpUtil.isAmqpUri(address)) { return; } final DmfActionRequest actionRequest = new DmfActionRequest(); actionRequest.setActionId(actionId); final Message message = getMessageConverter().toMessage(actionRequest, createConnectorMessagePropertiesEvent(tenant, controllerId, EventTopic.CANCEL_DOWNLOAD)); amqpSenderService.sendMessage(message, address); }
Example #21
Source File: RabbitMqTracingAutoConfigurationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 5 votes |
@Test public void send_withExchangeAndRoutingKey_shouldBeTraced() { // given Message requestMessage = createMessage(); // when rabbitTemplate.send(EXCHANGE, ROUTING_KEY, requestMessage); // then assertConsumerAndProducerSpans(0, ROUTING_KEY); }
Example #22
Source File: RabbitMqTracingManualConfigurationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 5 votes |
@Test public void sendAndReceive_withExchangeRoutingKeyAndMessage_shouldBeTraced() { // given Message requestMessage = createMessage(); // when Message response = rabbitTemplate.sendAndReceive(EXCHANGE, ROUTING_KEY, requestMessage); // then assertConsumerAndProducerSpans(0, ROUTING_KEY); assertOnResponse(response); }
Example #23
Source File: RabbitOrderMessagingService.java From spring-in-action-5-samples with Apache License 2.0 | 5 votes |
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 File: AmqpMessageHandlerServiceIntegrationTest.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Test @Description("Tests invalid null message content. This message should forwarded to the deadletter queue") @ExpectEvents({@Expect(type = TargetCreatedEvent.class, count = 0)}) public void updateActionStatusWithNullContent() { final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, null); getDmfClient().send(eventMessage); verifyOneDeadLetterMessage(); }
Example #25
Source File: AbstractAmqpServiceIntegrationTest.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
protected Message createUpdateAttributesMessage(final String target, final String tenant, final DmfAttributeUpdate attributeUpdate) { final MessageProperties messageProperties = createMessagePropertiesWithTenant(tenant); messageProperties.getHeaders().put(MessageHeaderKey.THING_ID, target); messageProperties.getHeaders().put(MessageHeaderKey.TYPE, MessageType.EVENT.toString()); messageProperties.getHeaders().put(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ATTRIBUTES.toString()); return createMessage(attributeUpdate, messageProperties); }
Example #26
Source File: DelayedSender.java From springboot-example with Apache License 2.0 | 5 votes |
public void send(String msg) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("发送时间:" + sf.format(new Date())); rabbitTemplate.convertAndSend(DelayedConfig.EXCHANGE_NAME, DelayedConfig.QUEUE_NAME, msg, new MessagePostProcessor() { @Override public Message postProcessMessage(Message message) throws AmqpException { message.getMessageProperties().setHeader("x-delay", 3000); return message; } }); }
Example #27
Source File: AmqpMessageHandlerServiceIntegrationTest.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Test @Description("Tests missing topic message header. This message should forwarded to the deadletter queue") @ExpectEvents({@Expect(type = TargetCreatedEvent.class, count = 0)}) public void missingTopicHeader() { final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, ""); eventMessage.getMessageProperties().getHeaders().remove(MessageHeaderKey.TOPIC); getDmfClient().send(eventMessage); verifyOneDeadLetterMessage(); }
Example #28
Source File: TypeAwareRabbitTemplate.java From articles with Apache License 2.0 | 5 votes |
public <T> T convertSendAndReceive(String exchange, String routingKey, Object message, ParameterizedTypeReference<T> responseType) { Message reply = convertSendAndReceiveRaw(exchange, routingKey, message, null, null); if (reply == null) { return null; } try { return mapper.readValue(reply.getBody(), mapper.getTypeFactory().constructType(responseType.getType())); } catch (Exception ex) { throw new RuntimeException("Exception while translating message"); } }
Example #29
Source File: RabbitMqTracingAutoConfigurationItTest.java From java-spring-rabbitmq with Apache License 2.0 | 5 votes |
@Test public void send_withoutExchangeAndRoutingKey_shouldBeTraced() { // given Message requestMessage = createMessage(); // when rabbitTemplate.send(requestMessage); // then assertConsumerAndProducerSpans(0, EMPTY_ROUTING_KEY); }
Example #30
Source File: AmqpMessageDispatcherServiceIntegrationTest.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Test @Description("Tests the download_only assignment: asserts correct dmf Message topic, and assigned DS") @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1), @Expect(type = TargetAssignDistributionSetEvent.class, count = 1), @Expect(type = ActionCreatedEvent.class, count = 1), @Expect(type = SoftwareModuleCreatedEvent.class, count = 3), @Expect(type = SoftwareModuleUpdatedEvent.class, count = 6), @Expect(type = DistributionSetCreatedEvent.class, count = 1), @Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) }) public void downloadOnlyAssignmentSendsDownloadMessageTopic() { final String controllerId = TARGET_PREFIX + "registerTargets_1"; final DistributionSet distributionSet = createTargetAndDistributionSetAndAssign(controllerId, DOWNLOAD_ONLY); final Message message = assertReplyMessageHeader(EventTopic.DOWNLOAD, controllerId); Mockito.verifyZeroInteractions(getDeadletterListener()); assertThat(message).isNotNull(); final Map<String, Object> headers = message.getMessageProperties().getHeaders(); assertThat(headers).containsEntry("thingId", controllerId); assertThat(headers).containsEntry("type", EVENT.toString()); assertThat(headers).containsEntry("topic", DOWNLOAD.toString()); final Optional<Target> target = controllerManagement.getByControllerId(controllerId); assertThat(target).isPresent(); // verify the DS was assigned to the Target final DistributionSet assignedDistributionSet = ((JpaTarget) target.get()).getAssignedDistributionSet(); assertThat(assignedDistributionSet.getId()).isEqualTo(distributionSet.getId()); }