org.springframework.messaging.handler.annotation.Headers Java Examples

The following examples show how to use org.springframework.messaging.handler.annotation.Headers. 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: App.java    From Mastering-Distributed-Tracing with MIT License 7 votes vote down vote up
@KafkaListener(topics = "message")
public void process(@Payload Message message, @Headers MessageHeaders headers) throws Exception {
    Span span = kafka.startConsumerSpan("process", headers);
    try (Scope scope = tracer.scopeManager().activate(span, true)) {
        System.out.println("Received message: " + message.message);
        if (message.image == null && message.message.trim().startsWith("/giphy")) {
            String query = message.message.split("/giphy")[1].trim();
            System.out.println("Giphy requested: " + query);
            message.image = giphy.query(query);
            if (message.image != null) {
                kafka.sendMessage(message);
                System.out.println("Updated message, url=" + message.image);
            }
        }
    }
}
 
Example #2
Source File: RabbitReceiver.java    From code with Apache License 2.0 7 votes vote down vote up
/**
 * 
 * 	spring.rabbitmq.listener.order.queue.name=queue-2
	spring.rabbitmq.listener.order.queue.durable=true
	spring.rabbitmq.listener.order.exchange.name=exchange-1
	spring.rabbitmq.listener.order.exchange.durable=true
	spring.rabbitmq.listener.order.exchange.type=topic
	spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
	spring.rabbitmq.listener.order.key=springboot.*
 * @param order
 * @param channel
 * @param headers
 * @throws Exception
 */
@RabbitListener(bindings = @QueueBinding(
		value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}", 
		durable="${spring.rabbitmq.listener.order.queue.durable}"),
		exchange = @Exchange(value = "${spring.rabbitmq.listener.order.exchange.name}", 
		durable="${spring.rabbitmq.listener.order.exchange.durable}", 
		type= "${spring.rabbitmq.listener.order.exchange.type}", 
		ignoreDeclarationExceptions = "${spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions}"),
		key = "${spring.rabbitmq.listener.order.key}"
		)
)
@RabbitHandler
public void onOrderMessage(@Payload com.bfxy.springboot.entity.Order order, 
		Channel channel, 
		@Headers Map<String, Object> headers) throws Exception {
	System.err.println("--------------------------------------");
	System.err.println("消费端order: " + order.getId());
	Long deliveryTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
	//手工ACK
	channel.basicAck(deliveryTag, false);
}
 
Example #3
Source File: UdpServer.java    From ProjectStudy with MIT License 6 votes vote down vote up
/**
   * 过滤器
   *
   * @param message
* @param headers
   * @return boolean
   * @throws
   * @author wliduo[[email protected]]
   * @date 2020/5/20 15:30
   */
  @Filter(inputChannel = "udpFilter", outputChannel = "udpRouter")
  public boolean filter(String message, @Headers Map<String, Object> headers) {
      // 获取来源Id
      String id = headers.get("id").toString();
      // 获取来源IP,可以进行IP过滤
      String ip = headers.get("ip_address").toString();
      // 获取来源Port
      String port = headers.get("ip_port").toString();
      // 信息数据过滤
      /*if (message.indexOf("-") < 0) {
          // 没有-的数据会被过滤
          return false;
      }*/
      return true;
  }
 
Example #4
Source File: HerdJmsMessageListener.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Processes a JMS message.
 *
 * @param payload the message payload.
 * @param allHeaders the JMS headers.
 */
@JmsListener(id = HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING,
    containerFactory = "jmsListenerContainerFactory", destination = HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING)
public void processMessage(String payload, @Headers Map<Object, Object> allHeaders)
{
    LOGGER.info("JMS message received from the queue. jmsQueueName=\"{}\" jmsMessageHeaders=\"{}\" jmsMessagePayload={}",
        HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING, allHeaders, payload);

    // Process the message as S3 notification.
    boolean messageProcessed = processS3Notification(payload);

    if (!messageProcessed)
    {
        // The message was not processed, log the error.
        LOGGER.error("Failed to process message from the JMS queue. jmsQueueName=\"{}\" jmsMessagePayload={}",
            HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING, payload);
    }
}
 
Example #5
Source File: JMSMailComsumer.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 6 votes vote down vote up
@JmsListener(destination = JMSType.SEND_MAIL)
public void sendMail(@Payload Object obj, @Headers MessageHeaders headers, Message message, Session session) {
	log.info("recived mail: {}", obj);

	System.out.println("-------------------------");
	System.out.println("obj:" + obj);
	System.out.println("headers:" + headers);
	System.out.println("message:" + message);
	System.out.println("session:" + session);
	System.out.println("-------------------------");

	if (obj instanceof MimeMessage) {
		mailSender.send((MimeMessage) obj);
	} else {
		mailSender.send((SimpleMailMessage) obj);
	}
}
 
Example #6
Source File: UdpServer.java    From ProjectStudy with MIT License 5 votes vote down vote up
/**
   * 路由分发处理器
   *
   * @param message
* @param headers
   * @return java.lang.String
   * @throws
   * @author wliduo[[email protected]]
   * @date 2020/5/20 15:35
   */
  @Router(inputChannel = "udpRouter")
  public String router(String message, @Headers Map<String, Object> headers) {
      // 获取来源Id
      String id = headers.get("id").toString();
      // 获取来源IP,可以进行IP过滤
      String ip = headers.get("ip_address").toString();
      // 获取来源Port
      String port = headers.get("ip_port").toString();
      // 筛选,走那个处理器
      if (false) {
          return "udpHandle2";
      }
      return "udpHandle1";
  }
 
Example #7
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@RuntimeUse
@SqsListener("testQueue")
public void receive(@Payload String payload,
		@Headers Map<String, String> headers) {
	this.payload = payload;
	this.headers = headers;
}
 
Example #8
Source File: QueueListenerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@RuntimeUse
@SqsListener("QueueListenerTest")
public void receiveMessage(String message,
		@Header(value = "SenderId", required = false) String senderId,
		@Headers Map<String, Object> allHeaders, SqsMessageHeaders asSqsHeaders) {
	LOGGER.debug("Received message with content {}", message);
	this.receivedMessages.add(message);
	this.senderId = senderId;
	this.allHeaders = allHeaders;
	this.approximateReceiveCount = asSqsHeaders.getApproximateReceiveCount();
	this.approximateFirstReceiveTimestamp = asSqsHeaders
			.getApproximateFirstReceiveTimestamp();
	this.timestamp = asSqsHeaders.getTimestamp();
	this.sentTimestamp = asSqsHeaders.getSentTimestamp();
	this.getCountDownLatch().countDown();
}
 
Example #9
Source File: StreamListenerAnnotatedMethodArgumentsTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@StreamListener
public void receive(
		@Input(Processor.INPUT) @Payload StreamListenerTestUtils.FooPojo fooPojo,
		@Headers Map<String, Object> headers,
		@Header(MessageHeaders.CONTENT_TYPE) String contentType) {
	this.receivedArguments.add(fooPojo);
	this.receivedArguments.add(headers);
	this.receivedArguments.add(contentType);
}
 
Example #10
Source File: StreamListenerAnnotatedMethodArgumentsTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@StreamListener(Processor.INPUT)
public void receive(@Payload StreamListenerTestUtils.FooPojo fooPojo,
		@Headers Map<String, Object> headers,
		@Header(MessageHeaders.CONTENT_TYPE) String contentType) {
	this.receivedArguments.add(fooPojo);
	this.receivedArguments.add(headers);
	this.receivedArguments.add(contentType);
}
 
Example #11
Source File: SmartPayloadArgumentResolver.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {
	return (!Message.class.isAssignableFrom(parameter.getParameterType())
			&& !MessageHeaders.class.isAssignableFrom(parameter.getParameterType())
			&& !parameter.hasParameterAnnotation(Header.class)
			&& !parameter.hasParameterAnnotation(Headers.class));
}
 
Example #12
Source File: StoragePolicyProcessorJmsMessageListener.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a JMS message.
 *
 * @param payload the message payload
 * @param allHeaders the JMS headers
 */
@JmsListener(id = HerdJmsDestinationResolver.SQS_DESTINATION_STORAGE_POLICY_SELECTOR_JOB_SQS_QUEUE,
    containerFactory = "storagePolicyProcessorJmsListenerContainerFactory",
    destination = HerdJmsDestinationResolver.SQS_DESTINATION_STORAGE_POLICY_SELECTOR_JOB_SQS_QUEUE)
public void processMessage(String payload, @Headers Map<Object, Object> allHeaders)
{
    LOGGER.info("Message received from the JMS queue. jmsQueueName=\"{}\" jmsMessageHeaders=\"{}\" jmsMessagePayload={}",
        HerdJmsDestinationResolver.SQS_DESTINATION_STORAGE_POLICY_SELECTOR_JOB_SQS_QUEUE, allHeaders, payload);

    // Process the message as storage policy selection message.
    try
    {
        // Process messages coming from the storage policy selector job.
        StoragePolicySelection storagePolicySelection = jsonHelper.unmarshallJsonToObject(StoragePolicySelection.class, payload);

        LOGGER.debug("Received storage policy selection message: businessObjectDataKey={} storagePolicyKey={} storagePolicyVersion={}",
            jsonHelper.objectToJson(storagePolicySelection.getBusinessObjectDataKey()),
            jsonHelper.objectToJson(storagePolicySelection.getStoragePolicyKey()), storagePolicySelection.getStoragePolicyVersion());

        // Process the storage policy selection message.
        storagePolicyProcessorService.processStoragePolicySelectionMessage(storagePolicySelection);
    }
    catch (RuntimeException | IOException e)
    {
        // Log a warning message if storage unit status is already ARCHIVED. Such error case is typically caused by a duplicate SQS message.
        if (e instanceof IllegalArgumentException &&
            e.getMessage().startsWith(String.format("Storage unit status is \"%s\"", StorageUnitStatusEntity.ARCHIVED)))
        {
            LOGGER.warn("Failed to process message from the JMS queue. jmsQueueName=\"{}\" jmsMessagePayload={}",
                HerdJmsDestinationResolver.SQS_DESTINATION_STORAGE_POLICY_SELECTOR_JOB_SQS_QUEUE, payload, e);
        }
        // Otherwise, log an error.
        else
        {
            LOGGER.error("Failed to process message from the JMS queue. jmsQueueName=\"{}\" jmsMessagePayload={}",
                HerdJmsDestinationResolver.SQS_DESTINATION_STORAGE_POLICY_SELECTOR_JOB_SQS_QUEUE, payload, e);
        }
    }
}
 
Example #13
Source File: SearchIndexUpdateJmsMessageListener.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a JMS message.
 *
 * @param payload the message payload
 * @param allHeaders the JMS headers
 */
@JmsListener(id = HerdJmsDestinationResolver.SQS_DESTINATION_SEARCH_INDEX_UPDATE_QUEUE,
    containerFactory = "jmsListenerContainerFactory",
    destination = HerdJmsDestinationResolver.SQS_DESTINATION_SEARCH_INDEX_UPDATE_QUEUE)
public void processMessage(String payload, @Headers Map<Object, Object> allHeaders)
{
    // Call the process message with retry private method.
    processMessageWithRetry(payload, allHeaders);
}
 
Example #14
Source File: RabbitManager.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@RabbitListener(
		bindings = @QueueBinding(
				value = @Queue, exchange = @Exchange(value = "input",
						durable = "true", autoDelete = "false", type = "topic"),
				key = "event2"))
public void newBook2(Book book, @Headers Map<String, String> headers) {
	LOG.info("newBook2 Received new book with bookname = " + book.getName());
	LOG.info("newBook2 Headers = " + headers);
	this.service.sendBook(book, headers.get("amqp_replyTo"));
}
 
Example #15
Source File: RabbitManager.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@RabbitListener(
		bindings = @QueueBinding(
				value = @Queue, exchange = @Exchange(value = "input",
						durable = "true", autoDelete = "false", type = "topic"),
				key = "event"))
public void newBook(Book book, @Headers Map<String, String> headers) {
	LOG.info("Received new book with bookname = " + book.getName());
	LOG.info("Headers = " + headers);
	this.service.sendBook(book, headers.get("amqp_replyTo"));
}
 
Example #16
Source File: MethodJmsListenerEndpointTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public void resolveHeaders(String content, @Headers Map<String, Object> headers) {
	invocations.put("resolveHeaders", true);
	assertEquals("Wrong payload resolution", "my payload", content);
	assertNotNull("headers not injected", headers);
	assertEquals("Missing JMS message id header", "abcd-1234", headers.get(JmsHeaders.MESSAGE_ID));
	assertEquals("Missing custom header", 1234, headers.get("customInt"));
}
 
Example #17
Source File: HeadersMethodArgumentResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private void handleMessage(
		@Headers Map<String, ?> param1,
		@Headers String param2,
		MessageHeaders param3,
		MessageHeaderAccessor param4,
		TestMessageHeaderAccessor param5) {
}
 
Example #18
Source File: HeadersMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {
	Class<?> paramType = parameter.getParameterType();
	return ((parameter.hasParameterAnnotation(Headers.class) && Map.class.isAssignableFrom(paramType)) ||
			MessageHeaders.class == paramType ||
			MessageHeaderAccessor.class.isAssignableFrom(paramType));
}
 
Example #19
Source File: App.java    From Mastering-Distributed-Tracing with MIT License 5 votes vote down vote up
@KafkaListener(topics = "message")
public void process(@Payload Message message, @Headers MessageHeaders headers) throws Exception {
    Span span = kafka.startConsumerSpan("process", headers);
    try (Scope scope = tracer.scopeManager().activate(span, true)) {
        System.out.println("Received message: " + message.message);
        redis.addMessage(message);
        System.out.println("Added message to room.");
    }
}
 
Example #20
Source File: HeadersMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
private void handleMessage(
		@Headers Map<String, ?> param1,
		@Headers String param2,
		MessageHeaders param3,
		MessageHeaderAccessor param4,
		TestMessageHeaderAccessor param5) {
}
 
Example #21
Source File: HeadersMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void supportsParameter() {

	assertTrue(this.resolver.supportsParameter(
			this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class)));

	assertTrue(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaders.class)));
	assertTrue(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaderAccessor.class)));
	assertTrue(this.resolver.supportsParameter(this.resolvable.arg(TestMessageHeaderAccessor.class)));

	assertFalse(this.resolver.supportsParameter(this.resolvable.annotPresent(Headers.class).arg(String.class)));
}
 
Example #22
Source File: MethodJmsListenerEndpointTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public void resolveHeaders(String content, @Headers Map<String, Object> headers) {
	this.invocations.put("resolveHeaders", true);
	assertEquals("Wrong payload resolution", "my payload", content);
	assertNotNull("headers not injected", headers);
	assertEquals("Missing JMS message id header", "abcd-1234", headers.get(JmsHeaders.MESSAGE_ID));
	assertEquals("Missing custom header", 1234, headers.get("customInt"));
}
 
Example #23
Source File: HeadersMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
private void handleMessage(
		@Headers Map<String, Object> param1,
		@Headers String param2,
		MessageHeaders param3,
		MessageHeaderAccessor param4,
		TestMessageHeaderAccessor param5) {
}
 
Example #24
Source File: HeadersMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveArgumentAnnotated() throws Exception {
	MethodParameter param = this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class);
	Object resolved = this.resolver.resolveArgument(param, this.message);

	assertTrue(resolved instanceof Map);
	@SuppressWarnings("unchecked")
	Map<String, Object> headers = (Map<String, Object>) resolved;
	assertEquals("bar", headers.get("foo"));
}
 
Example #25
Source File: HeadersMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void resolveArgumentAnnotated() {
	MethodParameter param = this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class);
	Map<String, Object> headers = resolveArgument(param);
	assertEquals("bar", headers.get("foo"));
}
 
Example #26
Source File: MethodJmsListenerEndpointTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
public void resolveHeaders(String content, @Headers Map<String, Object> headers) {
	this.invocations.put("resolveHeaders", true);
	assertEquals("Wrong payload resolution", "my payload", content);
	assertNotNull("headers not injected", headers);
	assertEquals("Missing JMS message id header", "abcd-1234", headers.get(JmsHeaders.MESSAGE_ID));
	assertEquals("Missing custom header", 1234, headers.get("customInt"));
}
 
Example #27
Source File: HeadersMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
private void handleMessage(
		@Headers Map<String, Object> param1,
		@Headers String param2,
		MessageHeaders param3,
		MessageHeaderAccessor param4,
		TestMessageHeaderAccessor param5) {
}
 
Example #28
Source File: HeadersMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void supportsParameter() {

	assertTrue(this.resolver.supportsParameter(
			this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class)));

	assertTrue(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaders.class)));
	assertTrue(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaderAccessor.class)));
	assertTrue(this.resolver.supportsParameter(this.resolvable.arg(TestMessageHeaderAccessor.class)));

	assertFalse(this.resolver.supportsParameter(this.resolvable.annotPresent(Headers.class).arg(String.class)));
}
 
Example #29
Source File: SearchIndexUpdateJmsMessageListener.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Processes a JMS message with retry.
 * This process message with retry method will attempt to process the message up to 4 times
 * with a 2 second, 4 second, 8 second, and 16 second exponential back off
 *
 * @param payload the message payload
 * @param allHeaders the JMS headers
 */
@Retryable(maxAttempts = 4, value = ListenerExecutionFailedException.class, backoff = @Backoff(delay = 2000, multiplier = 2))
private void processMessageWithRetry(String payload, @Headers Map<Object, Object> allHeaders)
{
    LOGGER.info("Message received from the JMS queue. jmsQueueName=\"{}\" jmsMessageHeaders=\"{}\" jmsMessagePayload={}",
        HerdJmsDestinationResolver.SQS_DESTINATION_SEARCH_INDEX_UPDATE_QUEUE, allHeaders, payload);
    try
    {
        // Unmarshall the SearchIndexUpdateDto from a JSON string to a SearchIndexUpdateDto object
        SearchIndexUpdateDto searchIndexUpdateDto = jsonHelper.unmarshallJsonToObject(SearchIndexUpdateDto.class, payload);

        LOGGER.info("Unmarshall the json payload into the searchIndexUpdateDto=\"{}\", jms_messageId=\"{}\"", searchIndexUpdateDto.toString(),
            allHeaders.get("jms_messageId"));

        // If the message type is null, this message is in the original message format.
        if (searchIndexUpdateDto.getMessageType() == null)
        {
            LOGGER.info("Updating the search index document(s) for the business object definition(s) that have changed. jms_messageId=\"{}\"",
                allHeaders.get("jms_messageId"));
            businessObjectDefinitionService.updateSearchIndexDocumentBusinessObjectDefinition(searchIndexUpdateDto);
        }
        else
        {
            switch (searchIndexUpdateDto.getMessageType())
            {
                case MESSAGE_TYPE_BUSINESS_OBJECT_DEFINITION_UPDATE:
                    LOGGER.info("Updating the search index document(s) for the business object definition(s) that have changed. jms_messageId=\"{}\"",
                        allHeaders.get("jms_messageId"));
                    businessObjectDefinitionService.updateSearchIndexDocumentBusinessObjectDefinition(searchIndexUpdateDto);
                    break;
                case MESSAGE_TYPE_TAG_UPDATE:
                    LOGGER.info("Updating the search index document(s) for the tag(s) that have changed. jms_messageId=\"{}\"",
                        allHeaders.get("jms_messageId"));
                    tagService.updateSearchIndexDocumentTag(searchIndexUpdateDto);
                    break;
                default:
                    LOGGER.error("Unknown message type.");
                    break;
            }
        }
    }
    catch (IOException ioException)
    {
        LOGGER.warn("Could not unmarshall JSON to SearchIndexUpdateDto object.", ioException);
    }
}
 
Example #30
Source File: HeadersMethodArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {
	Class<?> paramType = parameter.getParameterType();
	return ((parameter.hasParameterAnnotation(Headers.class) && Map.class.isAssignableFrom(paramType)) ||
			MessageHeaders.class == paramType || MessageHeaderAccessor.class.isAssignableFrom(paramType));
}